0

I would like to access the methods of a struct, which I get via a function that returns a Box<dyn Trait>.

I have the following example:

pub struct A;

impl A {
    fn foo(&self) {
        println!("foo");
    }
}

pub struct B;

impl B {
    fn bar(&self) {
        println!("bar");
    }
}

pub trait MyTrait {
    fn method_one(&self);
}

impl MyTrait for A {
    fn method_one(&self) {
        println!("this is for A");
    }
}

impl MyTrait for B {
    fn method_one(&self) {
        println!("this is for B");
    }
}

fn something(input: bool) -> Box<dyn MyTrait> {
    if input {
        return Box::new(A);
    } else {
        return Box::new(B);
    }
}

fn main() {
    let a = something(true);
    println!("{:?}", a.method_one()); //runs

    let b = something(false);
    println!("{:?}", b.method_one()); //runs

    println!("{:?}", a.foo()); //won't compile
}

I got the following compiler error:

error[E0599]: no method named `foo` found for struct `Box<dyn MyTrait>` in the current scope

Which struct exactly will be returned, depends on other factors. The only certainty is that it will be a struct that implements the MyTrait trait. That's why I return a dyn MyTrait from the function something().

I want do something like:

if a [is an A] {
    println!("{:?}", a.foo());
} else {
    println!("{:?}", a.bar());
}

Any idea how could I handle this?

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
ph0llux
  • 21
  • 2
  • How you should handle it depends on what you're trying to achieve, can you add more context to your question explaining why you're casting these structs to trait objects in the first place? – pretzelhammer Dec 10 '20 at 14:55
  • I tried to clarify it a little bit. :) – ph0llux Dec 10 '20 at 15:17
  • 1
    Does this answer your question? [How to get a reference to a concrete type from a trait object?](https://stackoverflow.com/q/33687447/2766908) Or this? [How to match trait implementors?](https://stackoverflow.com/q/26126683/2766908) – pretzelhammer Dec 10 '20 at 15:20
  • Yes...thanks, both answers fit my question. :) – ph0llux Dec 10 '20 at 15:31

0 Answers0