Marcus
Marcus

Reputation: 5245

Is it possible (in any way) to pass a trait object to a generic method?

I have a boxed trait object; I was wondering if, in any way, this can be passed to a method with a generic type bound:

trait Trait {
    fn tmethod(&self) {
        println!("hello");
    }
}

impl Trait for Vec<i32> {}

fn call_tmethod<T: Trait>(t: T) {
    t.tmethod();
}

fn main() {
    let obj: Box<dyn Trait> = Box::new(vec![0]);

    call_tmethod(obj);
}

Upvotes: 2

Views: 896

Answers (1)

Netwave
Netwave

Reputation: 42678

Usually there should be no problem since Box implements AsRef

use core::fmt::Display;


trait Foo {
    fn foo(&self) {
        println!("hello");    
    }
}

impl Foo for i32 {}

fn display<T: Foo>(t: &T) {
    t.foo();
}


fn main() {
    let foo = Box::new(10);
    display(foo.as_ref());
}

Playground

Notice that the method actually takes a reference & to the object instead. Otherwise you would have to implement the trait for &T where T: Foo, something like:

impl<T: Foo> Foo for &T { ... }

Upvotes: 2

Related Questions