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?