HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

How to match trait implementors

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
matchimplementorshowtrait

Problem

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 {
if v {
Box::new(Foo { x: 5 })
} else {
Box::new(Bar { y: 10 })
}
}

fn main() {
let f: Box = test(true);

match *f {
Foo { x } => println!("it was Foo: {}!", x),
Bar { y } => println!("it was Bar: {}!", y),
}
}


(Playground)

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

Solution

You can't. Traits do not support downcasting - Rust is not inheritance/subtyping-based language, and it gives you another set of abstractions. Moreover, what you want to do is unsound - traits are open (everyone can implement them for anything), so even if in your case match *f covers all possible cases, in general the compiler can't know that.

You have two options here. If you know the set of structures implementing your trait in advance, just use enum, it's a perfect tool for this. They allow you to statically match on a closed set of variants:

enum FooBar {
Foo(u32),
Bar(u32),
}

fn test(v: bool) -> FooBar {
if v {
FooBar::Foo(5)
} else {
FooBar::Bar(10)
}
}

fn main() {
let f: FooBar = test(true);

// Now that we have a
Box (*f makes it a Base),
// let's handle different cases:
match f {
FooBar::Foo(x) => println!("it was Foo: {}!", x),
FooBar::Bar(y) => println!("it was Bar: {}!", y),
}
}


(Playground)

This is by far the simplest way and it should always be preferred.

Another way is to use Any trait. It is a facility for type-safe downcasting from trait objects to regular types:

use std::any::Any;

struct Foo {
x: u32,
}
struct Bar {
y: u32,
}

fn test(v: bool) -> Box {
if v {
Box::new(Foo { x: 5 })
} else {
Box::new(Bar { y: 10 })
}
}

fn main() {
let f: Box = test(true);

match f.downcast_ref::() {
Some(&Foo { x }) => println!("it was Foo: {}!", x),
None => match f.downcast_ref::() {
Some(&Bar { y }) => println!("it was Bar: {}!", y),
None => unreachable!(),
},
}

// it will be nicer when
if let lands
// if let Some(ref Foo { x }) = f.downcast_ref::() {
// println!("it was Foo: {}!", x);
// } else if let Some(ref Bar { y }) = f.downcast_ref::() {
// println!("it was Bar: {}!", y);
// } else { unreachable!() }
}


(Playground)

Ideally it should be possible to write something like this:

trait Base: Any {}

impl Base for Foo {}
impl Base for Bar {}


and then use Base in the code, but it can't be done now because trait inheritance does not work with trait objects (e.g it is impossible to go from Box to Base).

Code Snippets

trait Base: Any {}

impl Base for Foo {}
impl Base for Bar {}

Context

Stack Overflow Q#26126683, score: 55

Revisions (0)

No revisions yet.