I have a library with the following code:
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()
}
And 2 other projects that use this library:
// case 1
let a = A {};
let b = B {};
test_ref(&a);
test_ref(&b);
and
// 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>`
}
The first case works fine but the second does not because it stores objects implementing MyTrait
in Box
objects so that they can be stored in a vector. Case 2 can't use references instead of Box
objects because there is no other variable to take the ownership of the underlying values.
Duplicating test_ref
function to handle a &Box<MyTrait>
instead of &MyTrait
and the exact same body works, but seems like a wrong solution and isn't possible if I can't have access to the content of the library that defines test_ref
. Is there any other way to handle both of these?