考虑以下代码:
use std::ops::Add;
trait Trait
where Self::Assoc: Add<Self::Assoc, Output=Self::Assoc>
+ for <'a> Add<&'a Self::Assoc, Output=Self::Assoc>
{
type Assoc;
fn get(&self) -> Self::Assoc;
}
fn add1<T: Trait>(x: T, y: T) -> T::Assoc {
x.get() + y.get()
}
Run Code Online (Sandbox Code Playgroud)
这无法编译:
error[E0308]: mismatched types
--> src/lib.rs:12:15
|
12 | x.get() + y.get()
| ^^^^^^^
| |
| expected reference, found associated type
| help: consider borrowing here: `&y.get()`
|
= note: expected reference `&<T as Trait>::Assoc`
found associated type `<T as Trait>::Assoc`
Run Code Online (Sandbox Code Playgroud)
我可以通过明确指定我想要使用的特征来解决这个问题:
fn add2<T: Trait>(x: T, y: T) -> T::Assoc {
<T::Assoc as Add<T::Assoc>>::add(x.get(), y.get())
}
Run Code Online (Sandbox Code Playgroud)
但我想知道:为什么会发生这种情况?另外,有没有更紧凑的工作?
请注意,特征边界的顺序很重要。如果我将它们更改为:
where Self::Assoc: for <'a> Add<&'a Self::Assoc, Output=Self::Assoc>
+ Add<Self::Assoc, Output=Self::Assoc>
Run Code Online (Sandbox Code Playgroud)
...然后add1编译正常,但这失败了:
fn add3<T: Trait>(x: T, y: T) -> T::Assoc {
x.get() + &y.get()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |