< 返回版块

github.com/shanliu/lsys 发表于 2020-12-09 15:10

trait Lt{}
impl Lt for i32{}
impl Lt for i8{}
fn bstest<T:Lt>()->T{
    let a:T=1;
    return a;
}
fn main() {
    bstest::<i8>();
}
//希望根据指定泛型返回对应类型
但上面代码提示错误
error[E0308]: mismatched types
  --> src\main.rs:19:13
   |
18 | fn bstest<T:Lt>()->T{
   |           - this type parameter
19 |     let a:T=1;
   |           - ^ expected type parameter `T`, found integer
   |           |
   |           expected due to this
   |
   = note: expected type parameter `T`
                        found type `{integer}`

error: aborting due to previous error; 9 warnings emitted

评论区

写评论
aariety 2020-12-09 21:15

方案一:直接用宏替代函数(如果只有i8, i32这种的话)

macro_rules! bstest {
    ( $type:ty ) => {
        (1 as $type)
    };
}

fn main() {
    println!("{:?}", bstest!(i8));
}

方案二:给 Lt 加个方法,让需要的类型实现它(可以用宏批量实现)

trait Lt {
    fn bstest() -> Self;
}

macro_rules! bstest_bounded {
    ($($type:ty),+) => {$(
        impl Lt for $type {
            fn bstest() -> Self {
                1
            }
        }
    )+}
}

bstest_bounded!(i8, i32);

fn bstest<T: Lt>() -> T {
    T::bstest()
}

fn main() {
    println!("{:?}", bstest::<i8>());
}
uno 2020-12-09 15:51

那何必再搞个Default呢,直接在trait Lt里面再加一个方法就完了嘛

--
👇
Cupnfish: ```rust trait Lt{} impl Lt for i32{} impl Lt for i8{}

fn bstest<T:Lt + Default>()->T{ num::() }

fn num<T:Default>() -> T { Default::default() }

fn main() { let a = bstest::(); println!("{}",a); }

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018
参考这种方法试试
Cupnfish 2020-12-09 15:41
trait Lt{}
impl Lt for i32{}
impl Lt for i8{}

fn bstest<T:Lt + Default>()->T{
    num::<T>()
}

fn num<T:Default>() -> T {
    Default::default()
}

fn main() {
    let a = bstest::<i8>();
    println!("{}",a);
}

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018 参考这种方法试试

1 共 3 条评论, 1 页