&dyn Foo_T | Bar_T

The answer is probably no, but asking just in case.

Is there anyway to express in Rust:

x: &dyn Foo_T | Bar_T

what this means here is: we do not know which, but we know that atleast one of the following is true:

x: &dyn Foo_T
x: &dyn Bar_T

and then at runtime, there is some dispatch and we figure out which one x implements

You can implement a trait for &dyn Foo_T and &dyn Bar_T and use that as your trait bound:

trait Foo {}
trait Bar {}

struct FooImpl;
struct BarImpl;

impl Foo for FooImpl {}
impl Bar for BarImpl {}

trait FooOrBar {}

impl FooOrBar for &dyn Foo {}
impl FooOrBar for &dyn Bar {}

fn foo_or_bar<T: FooOrBar>(_: T) {}

fn main() {
    foo_or_bar(&FooImpl as &dyn Foo);
    foo_or_bar(&BarImpl as &dyn Bar);
}

Playground.

You could use the either crate, and do it like below. Downside is that your parameter can only implement one trait or the other; both is no longer an option.

trait Foo_T {}
trait Bar_T {}

fn my_func(e: Either<&dyn Foo_T, &dyn Bar_T>) {
    match e {
        Either::Left(foo) => {}
        Either::Right(bar) => {}
    }
}

1 Like