Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading