![](/img/trans.png)
[英]Why doesn't a trait implementation compile for a struct, but it compiles for a reference to the struct?
[英]Rust can't find trait implementation
我正在嘗試為實現另一個特征的任何東西(在示例代碼中為Test
trait)實現Add
trait。 我在Add
實現中使用引用,因為並非所有實現Test
東西都具有相同的大小。 下面的代碼可以正常編譯:
use std::ops::Add;
struct Foo(i32);
struct Bar(i64);
trait Test {}
impl Test for Foo {}
impl Test for Bar {}
impl<'a, 'b> Add<&'b Test> for &'a Test {
type Output = Box<Test>;
fn add(self, other: &'b Test) -> Box<Test> {
if true {
Box::new(Foo(5))
} else {
Box::new(Bar(5))
}
}
}
如下所述,當我嘗試實際使用Add
,它說該操作無法應用,因為缺少Add
for &Foo
的實現。
fn test_add() {
&Foo(5) + &Bar(5)
}
我是否定義了錯誤的實現? 我打錯了嗎? 我們的目標是使附加功能需要兩個引用這兩個實施對象Test
,並返回一個引用(或箱),以實現一個新的對象Test
(和可能不是相同的基本類型,其中一個輸入)。
我發現了另一種方法,可以稍微改變行為,但可以。
struct V<T>(T);
use std::ops::Add;
impl<T1: Test, T2: Test> Add<V<Box<T2>>> for V<Box<T1>> {
type Output = V<Box<Test>>;
fn add(self, other: V<Box<T2>>) -> Self::Output {
unimplemented!()
}
}
這樣一來,它就可以返回實現Test
任何類型,但需要將所有內容包裝在Box
和虛擬結構V
。 不是很優雅,我仍然不明白為什么我的原始代碼不起作用,但是至少它具有我想要的行為。
問題在於,編譯器無法將&Foo
隱式轉換為&Test
。 如果首先將其顯式轉換為&Test
,則運算符重載將起作用:
fn test_add() {
let foo: &Test = &Foo(5);
foo + &Bar(5);
}
另外,您可以使用完全限定的語法 :
fn test_add() {
<&Test as Add<&Test>>::add(&Foo(5), &Bar(5));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.