【发布时间】:2020-05-15 22:42:42
【问题描述】:
我有以下代码:
struct X { i: i32 }
trait MyTrait<T> {
fn hello(&self);
}
impl MyTrait<i32> for X {
fn hello(&self) { println!("I'm an i32") }
}
impl MyTrait<String> for X {
fn hello(&self) { println!("I'm a String") }
}
fn main() {
let f = X { i: 0 };
f.hello();
}
这显然无法编译,因为编译器无法消除 f.hello() 属于哪个特征的歧义。所以我得到了错误
error[E0282]: type annotations needed
--> src\main.rs:17:7
|
17 | f.hello();
| ^^^^^ cannot infer type for type parameter `T` declared on the trait `MyTrait`
有没有办法注释hello 的类型,所以我可以告诉编译器例如在f 上调用MyTrait<String>::hello?
【问题讨论】:
标签: rust