try_as_dyn

Function try_as_dyn 

Source
pub const fn try_as_dyn<T: Any + 'static, U: Pointee<Metadata = DynMetadata<U>> + ?Sized + 'static>(
    t: &T,
) -> Option<&U>
🔬This is a nightly-only experimental API. (try_as_dyn #144361)
Expand description

Returns Some(&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;

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 dog = Dog;
let rock = Rock;

let as_animal: Option<&dyn Animal> = try_as_dyn::<Dog, dyn Animal>(&dog);
assert_eq!(as_animal.unwrap().speak(), "woof");

let not_an_animal: Option<&dyn Animal> = try_as_dyn::<Rock, dyn Animal>(&rock);
assert!(not_an_animal.is_none());