我有一个包含以下代码的库:
pub trait MyTrait {
fn do_something(&self);
}
struct A { }
impl MyTrait for A {
fn do_something(&self) {
println!("A");
}
}
struct B { }
impl MyTrait for B {
fn do_something(&self) {
println!("B");
}
}
fn test_ref(t: &MyTrait) {
// this function does many things here with t
// ...
t.do_something()
}
以及其他2个使用此库的项目:
// case 1
let a = A {};
let b = B {};
test_ref(&a);
test_ref(&b);
和
// case 2
let list: Vec<Box<MyTrait>> = vec![Box::new(A {}), Box::new(B {})];
for item in &list {
test_ref(item); // error: the trait `MyTrait` is not implemented for `std::boxed::Box<MyTrait>`
}
第一种情况正常但第二种情况不正常,因为它在MyTrait
个对象中存储实现Box
的对象,以便它们可以存储在向量中。情况2不能使用引用而不是Box
个对象,因为没有其他变量可以获取基础值的所有权。
复制test_ref
函数来处理&Box<MyTrait>
代替&MyTrait
并且完全相同的正文有效,但似乎是一个错误的解决方案,如果我可以&#39则不可能; t可以访问定义test_ref
的库的内容。有没有其他方法来处理这两个?