Trait amplify::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 ::core::any::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]
extern crate amplify_derive;
extern crate amplify;
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§