Search code examples
rustunsafe

Can I safely cast Box<dyn Any + Send> to Box<dyn Any>?


Send is a marker trait, and does not have any impact on memory layout. That said, the mechanics of the Any type remain slightly mysterious to me.

Is the following code sound and does it do what I want: the cast type will always downcast correctly to the original concrete type:

let what_i_have: Box<dyn Any + Send> = Box::new(69);
let ptr = Box::into_raw(what_i_have);
let what_i_want: Box<dyn Any> = unsafe { Box::from_raw(ptr as *mut dyn Any) };

I've played around with this, and it "seems to work fine". Is it?

As a bonus question, can I do this without the unsafe block?


Solution

  • Yes, you can do this safely by assigning the value:

    use std::any::Any;
    
    fn main() {
        let what_i_have: Box<dyn Any + Send> = Box::new(69);
        let what_i_want: Box<dyn Any> = what_i_have;
    }
    

    See also: