amplify

Trait AsAny

Source
pub trait AsAny {
    // Required method
    fn as_any(&self) -> &dyn Any;
}
Expand description

Trait AsAny allows simple conversion of any type into a generic “thick” pointer &dyn Any (see Any), that can be later converted back to the original type with a graceful failing for all other conversions. For simple conversions it is recommended to use #[derive(AsAny)] macro from amplify_derive crate (see amplify_derive::AsAny).

§Example

#[macro_use]
use amplify::AsAny;

#[derive(AsAny, Copy, Clone, PartialEq, Eq, Debug)]
struct Point {
    pub x: u64,
    pub y: u64,
}

#[derive(AsAny, PartialEq, Debug)]
struct Circle {
    pub radius: f64,
    pub center: Point,
}

let mut point = Point { x: 1, y: 2 };
let point_ptr = point.as_any();

let mut circle = Circle {
    radius: 18.,
    center: point,
};
let circle_ptr = circle.as_any();

assert_eq!(point_ptr.downcast_ref(), Some(&point));
assert_eq!(circle_ptr.downcast_ref(), Some(&circle));
assert_eq!(circle_ptr.downcast_ref::<Point>(), None);

let p = point_ptr.downcast_ref::<Point>().unwrap();
assert_eq!(p.x, 1)

Required Methods§

Source

fn as_any(&self) -> &dyn Any

Returns thick pointer of &dyn Any type, that can be later downcasted back to a reference of the original type.

Implementations on Foreign Types§

Source§

impl AsAny for i8

Source§

fn as_any(&self) -> &dyn Any

Source§

impl AsAny for i16

Source§

fn as_any(&self) -> &dyn Any

Source§

impl AsAny for i32

Source§

fn as_any(&self) -> &dyn Any

Source§

impl AsAny for i64

Source§

fn as_any(&self) -> &dyn Any

Source§

impl AsAny for i128

Source§

fn as_any(&self) -> &dyn Any

Source§

impl AsAny for u8

Source§

fn as_any(&self) -> &dyn Any

Source§

impl AsAny for u16

Source§

fn as_any(&self) -> &dyn Any

Source§

impl AsAny for u32

Source§

fn as_any(&self) -> &dyn Any

Source§

impl AsAny for u64

Source§

fn as_any(&self) -> &dyn Any

Source§

impl AsAny for u128

Source§

fn as_any(&self) -> &dyn Any

Source§

impl AsAny for usize

Source§

fn as_any(&self) -> &dyn Any

Source§

impl AsAny for String

Source§

fn as_any(&self) -> &dyn Any

Implementors§