0

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Carl Levasseur
  • 4,203
  • 3
  • 19
  • 19
  • As the error messages indicates: *the trait `MyTrait` is not implemented for `std::boxed::Box`* — so implement the trait for that type :-) – Shepmaster Sep 23 '17 at 14:01
  • As Rust has [deref coercion](https://doc.rust-lang.org/book/second-edition/ch15-02-deref.html) and Box deref to &T, you would better write a method. – LoganMzz Sep 25 '17 at 21:29

0 Answers0