Casting std::any::Any to any trait

It is possible to cast Box to any struct type using downcast_ref, but how ca trait cast can implemented even if it is unsafe, but i know for sure that the stored object has this trait? Maybe I should use some custom base trait and implement it for any used type?

No, Any doesn't support downcasting to traits. The custom method to get it as the trait is the way to go.

So I need to store a different "base" trait inside the Box? Something like Box<dyn Castable>? I tried to that, but I need a generic function on the trait, so I can cast to any type, but it violates object safety as I understand

If you want to cast to any statically-known type, then that's really just Any itself.

struct DataHolder {
    data: Box<dyn std::any::Any>
}

impl DataHolder {
    pub fn cast<T: 'static>(&self) -> Option<&T> {
        self.data.downcast_ref::<T>()
    }
}

struct TestStruct {
    data: u32
}

trait TestTrait {
    fn foo(&self) {
        println!("TEST")
    }
}

impl TestTrait for TestStruct {}

fn main() {
    let data_holder = DataHolder { data: Box::new(TestStruct {data: 0 }) };
    
    data_holder.cast::<TestStruct>().unwrap().foo();
    
    // How I can do something like this?
    //data_holder.cast::<TestTrait>().unwrap().foo();
}

Here is an example of what i am trying to achieve. What should i use istead of downcast?

You need to click "Share" and then "Permalink to the playground" for the playground URL (and you probably want edition 2018). Assuming it's the same as the block in your comment: Playground

Thank you. I have updated the post

Maybe this?

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1d9496b27c19727198dfe725180c3e78

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.