Downcasting borrowed box

A downcast() method such as Rust Box requires that the call site have full ownership of the Box instance. There seems to be no equivalent that can work with a borrowed link. Is there a reason for this? Is there a workaround that will work on a borrowed instance?

+6
source share
1 answer

There is an alternative, but this is not the Box method: it Any::downcast_ref() . Thanks to the deref conversion and Box es Deref -impl, you can directly call T methods on Box<T> . This way you can directly call Any::downcast_ref() on Box<Any> :

 let b: Box<Any> = Box::new(27u64); // The type of `ref_a` and `ref_b` is `&u64` let ref_a = b.downcast_ref::<u64>().unwrap(); let ref_b = b.downcast_ref::<u64>().unwrap(); println!("{} == {}", ref_a, ref_b); 

There is also Any::downcast_mut() to get a mutable link.

+9
source

Source: https://habr.com/ru/post/1014751/


All Articles