I swear I searched the entire Internet, and I tried very hard to understand all the answers that I found that were related. However, I still do not understand if this is possible or not.
trait Foo {
fn do_foo (&self);
}
trait Bar {
fn do_bar (&self);
}
struct SomeFoo;
impl Foo for SomeFoo {
fn do_foo(&self) {
println!("doing foo");
}
}
struct SomeFooBar;
impl Foo for SomeFooBar {
fn do_foo(&self) {
println!("doing foo");
}
}
impl Bar for SomeFooBar {
fn do_bar(&self) {
println!("doing bar");
}
}
fn main () {
let foos:Vec<Box<Foo>> = vec!(Box::new(SomeFoo), Box::new(SomeFooBar));
for foo in foos {
foo.do_foo();
}
}
Playpen: http://is.gd/CPnSCu
My question is mainly if there is a way to drop from one sign to another.
I have two traits Fooand Barand a Vec<Box<Foo>>. I know that some elements in vec implement the trait Bar, and I wonder if there is a way I could target them?
Update
The only solution that I have found so far is to introduce the 3rd sign FooOrBarwith explicit conversion methods and implement this for both types. This doesn't seem like the right tool to work though;)
trait FooOrBar {
fn to_bar(&self) -> Option<&Bar>;
fn to_foo(&self) -> Option<&Foo>;
}
impl FooOrBar for SomeFooBar {
fn to_bar(&self) -> Option<&Bar> {
Some(self)
}
fn to_foo(&self) -> Option<&Foo> {
None
}
}
impl FooOrBar for SomeFoo {
fn to_bar(&self) -> Option<&Bar> {
None
}
fn to_foo(&self) -> Option<&Foo> {
Some(self)
}
}
fn main () {
let foos:Vec<Box<FooOrBar>> = vec!(Box::new(SomeFoo), Box::new(SomeFooBar));
for foo in foos {
foo.to_foo().map(|foo| foo.do_foo());
foo.to_bar().map(|foo| foo.do_bar());
}
}