pub const fn try_as_dyn_mut<T: Any + 'static, U: Pointee<Metadata = DynMetadata<U>> + ?Sized + 'static>(
t: &mut T,
) -> Option<&mut U>🔬This is a nightly-only experimental API. (
try_as_dyn #144361)Expand description
Returns Some(&mut U) if T can be coerced to the trait object type U. Otherwise, it returns None.
§Compile-time failures
Determining whether T can be coerced to the trait object type U requires compiler trait resolution.
In some cases, that resolution can exceed the recursion limit,
and compilation will fail instead of this function returning None.
§Examples
#![feature(try_as_dyn)]
use core::any::try_as_dyn_mut;
trait Animal {
fn speak(&self) -> &'static str;
}
struct Dog;
impl Animal for Dog {
fn speak(&self) -> &'static str { "woof" }
}
struct Rock; // does not implement Animal
let mut dog = Dog;
let mut rock = Rock;
let as_animal: Option<&mut dyn Animal> = try_as_dyn_mut::<Dog, dyn Animal>(&mut dog);
assert_eq!(as_animal.unwrap().speak(), "woof");
let not_an_animal: Option<&mut dyn Animal> = try_as_dyn_mut::<Rock, dyn Animal>(&mut rock);
assert!(not_an_animal.is_none());