Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::any::{Any, TypeId};
- use std::borrow::Borrow;
- use std::mem;
- pub struct Dynamic {
- pub type_id: TypeId,
- val: Box<dyn Any + Send + Sync>,
- }
- impl<T> From<T> for Dynamic where T: Any + Send + Sync {
- fn from(val: T) -> Self {
- Dynamic {
- type_id: TypeId::of::<T>(),
- val: Box::new(val),
- }
- }
- }
- impl<T: Any + Send + Sync> Dynamic {
- pub fn this<T>(&self) -> (bool, &T) {
- match self.val.downcast::<T>() {
- Ok(val) => (true, val.borrow()),
- Err(_) => (false, Box::new(unsafe { mem::zeroed() } ))
- }
- }
- pub fn am(&self) -> (bool, &T) {
- (true, self.borrow())
- }
- }
- #[test]
- fn test() {
- let object = Dynamic::from("test");
- assert_eq!(object.am(), object.this::<&str>())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement