我正在尝试为任何实现另一个特性(在示例代码中为 Test
特性)的东西实现 Add
特性。我在 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
时,如下所示,它说该操作无法应用,因为 &Foo
的 Add
实现> 不见了。
fn test_add() {
&Foo(5) + &Bar(5)
}
我是否错误地定义了实现?我叫错了吗?目标是使函数 add 接受两个对都实现 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
中。不是很优雅,我仍然不明白为什么我的原始代码不起作用,但至少这具有我想要的行为。
关于reference - Rust 找不到特征实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51867505/