ruststructtraitsbox

cast struct that not explictly impl a trait to the trait object?


If there is a struct NotTFoo has a method called say_hi that statifies TFoo trait but not explictly impl TFoo, is it possible to use NotTFoo as a TFoo trait object?

// the trait
trait TFoo {
    fn say_hi(&self);
}

// NotFoo doesn't explictly implement TFoo, but it has a say_hi same as TFoo's
struct NotTFoo {}

impl NotTFoo {
    fn say_hi(&self) {}
}

// bar is a trait object
struct Bar{
    bar: Option<Box<dyn TFoo>>
}


// the trait bound `NotTFoo: TFoo` is not satisfied
// required for the cast from `NotTFoo` to the object type `dyn TFoo`r
fn main() {
    let not_foo = NotTFoo{};
    let boxed = Box::new(not_foo) as Box<dyn TFoo>; // Error
    let bar = Bar {bar: Some(boxed)};
}

Can I cast NotTFoo to dyn TFoo?

the trait bound NotTFoo: TFoo is not satisfied required for the cast from NotTFoo to the object type dyn TFoo


Solution

  • No, Rust does not use duck-typing or structural-typing to determine if a type implements a trait. It must be explicitly declared.