0

Given an array of objects that implement a specific trait, I would like to iterate over them and run a function that takes a boxed trait, as follows:

use std::boxed::Box;

trait MyTrait {
    fn go(&self);
}

struct MyStruct1 {}

struct MyStruct2 {}

impl MyTrait for MyStruct1 {
    fn go(&self) {
        println!("Go MyStruct1");
    }
}

impl MyTrait for MyStruct2 {
    fn go(&self) {
        println!("Go MyStruct2");
    }
}

fn go_boxed(t: Box<MyTrait>) {
    t.go();
}

fn main() {
    let t1 = MyStruct1 {};
    let t2 = MyStruct2 {};
    let ts: Vec<&MyTrait> = vec![&t1, &t2];
    go_boxed(Box::from(t1));
    go_boxed(Box::from(t2));
    // This will fail:
    ts.into_iter()
        .for_each(|x| go_boxed(Box::new(x) as Box<MyTrait>));
}

Error:

error[E0277]: the trait bound `&dyn MyTrait: MyTrait` is not satisfied
  --> src/main.rs:35:32
   |
35 |         .for_each(|x| go_boxed(Box::new(x) as Box<MyTrait>));
   |                                ^^^^^^^^^^^ the trait `MyTrait` is not implemented for `&dyn MyTrait`
   |
   = note: required for the cast to the object type `dyn MyTrait`

What is happening? How can I work with vector of elements without knowing the concrete type of each element?

The referred question does not face my more trivial issue, which is why it is not compiling.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
fcracker79
  • 1,118
  • 13
  • 26
  • 1
    https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=579abbf444fa26b5a95de5dc61d63da1 – Stargateur Jul 22 '19 at 20:08
  • @Stargateur thanks for the answer. Unfortunately here I cannot even compile it and I do not know why. – fcracker79 Jul 22 '19 at 20:09
  • 3
    Your main problem is unrelated to dynamic method binding for trait objects. The `go_boxed()` function takes ownership of its argument, but the vector you are iterating over only has references, so you can't pass ownership to the function. This problem would also occur if your object type was, say, `String` rather than a trait object. – Sven Marnach Jul 22 '19 at 20:12
  • @Stargateur ok thanks for the snippet of code. I am just studying the language and I do not understand what is wrong with my code. My objective as first is to understand what is happening. – fcracker79 Jul 22 '19 at 20:13
  • 1
    @fcracker79 yes, but explain what is happening will not make you understand better I think. You are actually trying something very strange in Rust. So you get a very strange error that I don't think the explanation will help you much because you will run into an other error very hard to understand. – Stargateur Jul 22 '19 at 20:19
  • [The duplicate applied to your situation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e9223adec01e9c1cb78775b73e47ef3e) – Shepmaster Jul 22 '19 at 23:05
  • 1
    Thanks all guys. – fcracker79 Jul 23 '19 at 12:10

0 Answers0