reference - Rust 找不到特征实现

标签 reference rust traits

我正在尝试为任何实现另一个特性(在示例代码中为 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 时,如下所示,它说该操作无法应用,因为 &FooAdd 实现> 不见了。

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/

相关文章:

c++ - 将 std::future 移动到另一个 std::future

Java 集合在提供引用的同时确保唯一性

process - 如何在不阻塞Rust的情况下读取子进程的输出?

rust - 可以强制执行Rust特征文档中列出的 “Laws”吗?

rust - 在为引用和非引用类型实现一个特性时,我是否必须实现它两次?

rust - 为什么要借这个?

Java 引用传递不起作用?

webpack - rust/Wasm : Module not found: Error: Can't resolve 'env' in

PHP Trait 碰撞构造函数

rust - 创建一个实现特定 Fn 接口(interface)的结构