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
1
共 3 条评论, 1 页
评论区
写评论方案一:直接用宏替代函数(如果只有i8, i32这种的话)
方案二:给 Lt 加个方法,让需要的类型实现它(可以用宏批量实现)
那何必再搞个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 参考这种方法试试