2

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);
}
Marcus
  • 5,104
  • 2
  • 28
  • 24
  • what is the problem? did you try to pass the object? – Netwave Apr 15 '22 at 13:00
  • It's possible if the trait object implements the trait, but that's not necessarily the case ([example 1](https://users.rust-lang.org/t/reference-trait-object-doesnt-implement-trait/12114), [example 2](https://users.rust-lang.org/t/boxed-trait-object-doesnt-impl-trait/24729)) and I think it's not the case by default because it's not always possible. – Masklinn Apr 15 '22 at 13:25
  • I think @Masklinn is correct - the error I get (when passing `as_ref()`) is `the trait bound `&dyn Trait: Trait` is not satisfied - the trait `Trait` is not implemented for `&dyn Trait`rustcE0277). – Marcus Apr 15 '22 at 14:34

1 Answers1

2

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 { ... }
Netwave
  • 40,134
  • 6
  • 50
  • 93