产生这个问题的原因是在使用 trait 声明关联类型时,它的参数是未知的。在函数调用中推断泛型参数可以解决这个问题。
以下是一个示例代码,其中的 Associated trait 声明了一个关联类型 Output:
trait Associated {
type Output;
fn associated(&self, t: T) -> Self::Output;
}
fn foo>(a: A, t: T) -> A::Output {
a.associated(t)
}
struct MyType(u32);
impl Associated for MyType {
type Output = (T, u32);
fn associated(&self, t: T) -> Self::Output {
(t, self.0)
}
}
fn main() {
let mytype = MyType(42);
let result = foo(mytype, "hello");
println!("result = {:?}", result);
}
在这里,foo 函数是泛型的,并返回一个 A::Output 类型的值,其中 A 必须是实现了 Associated trait 的类型。
MyType 结构体实现了 Associated,其中 Output 被定义为一个元组 (T, u32),函数 associated 将构造和返回该元组。
在 main 函数中,使用 MyType 的实例调用 foo,并传递 "hello" 的字符串字面量作为第二个参数。由于 foo 函数中的 T 是从参数推断获得的,因此没有未推断的泛型参数,所以不会出现编译错误。