I have a trait that is implemented by some structs. I want to write a pattern match where I can handle every possible case:
trait Base {}
struct Foo {
x: u32,
}
struct Bar {
y: u32,
}
impl Base for Foo {}
impl Base for Bar {}
fn test(v: bool) -> Box<Base + 'static> {
if v {
Box::new(Foo { x: 5 })
} else {
Box::new(Bar { y: 10 })
}
}
fn main() {
let f: Box<Base> = test(true);
match *f {
Foo { x } => println!("it was Foo: {}!", x),
Bar { y } => println!("it was Bar: {}!", y),
}
}
I'm getting this compilation error:
error[E0308]: mismatched types
--> src/main.rs:25:9
|
25 | Foo { x } => println!("it was Foo: {}!", x),
| ^^^^^^^^^ expected trait Base, found struct `Foo`
|
= note: expected type `dyn Base`
found type `Foo`
error[E0308]: mismatched types
--> src/main.rs:26:9
|
26 | Bar { y } => println!("it was Bar: {}!", y),
| ^^^^^^^^^ expected trait Base, found struct `Bar`
|
= note: expected type `dyn Base`
found type `Bar`