AnimalT -> Option<Cat>

Suppose we have:


pub struct Cat {}

pub struct Dog {}

pub trait Animal_T {}

impl Animal_T for Cat {}

impl Animal_T for Dog {}

is there a safe way to do

&dyn Animal_T -> Option<&Cat> or
Rc<dyn Animal_T> -> Option<Rc<Cat>> or
... something like this ...

Thanks!

Not directly. Typically, this is done via one of two mechanisms:

  1. Using Any, by adding something like an Animal_T::as_any method.
  2. Implementing manual Animal_T::as_cat etc. methods.
1 Like

Not using this method (long story, involves compilation time / crate dependencies.)

Is the idea here Animal_T -> Any -> downcast to Option<Cat> ?

It's that or implement it yourself with unsafe ala dyn Error.

2 Likes

Use downcast_rs - Rust.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.