Function trait_dyn_dispatch

Source
pub fn trait_dyn_dispatch()
Expand description

§动态分发

## trait 对象

用泛型模拟 Class

```rust

#![allow(unused)]

use core::any::{Any,TypeId};
use std::sync::Arc;

/// Class definition
struct Class {
    /// The name of the class
    name: String,
    /// The corresponding Rust type
    type_id: TypeId,
}

impl Class {
    /// Create a new class definition for the type `T`
    fn new<T: 'static>() -> Self {
        Self {
            name: std::any::type_name::<T>().to_string(),
            type_id: TypeId::of::<T>(),
        }
    }
}

/// An instance of a class
struct Instance {
    inner: Arc<dyn Any>, // `Arc` because we don't need/want mutability
}

impl Instance {
    /// Construct a new `Instance` from a type that
    /// implements `Any` (i.e. any sized type).
    fn new(obj: impl Any) -> Self {
        Self {
            inner: Arc::new(obj)
        }
    }
}

impl Instance {
    /// Check whether this is an instance of the provided class
    fn instance_of(&self, class: &Class) -> bool {
        // self.inner.type_id() == class.type_id
        self.inner.as_ref().type_id() == class.type_id
    }
}

struct Foo {}
struct Bar {}

fn main(){


    let foo_class: Class = Class::new::<Foo>();
    let bar_class: Class = Class::new::<Bar>();
    let foo_instance: Instance = Instance::new(Foo {});

    assert!(foo_instance.instance_of(&foo_class));
    assert!(!foo_instance.instance_of(&bar_class));
}
```