Skip to content

Instantly share code, notes, and snippets.

@antoninhrlt
Created February 18, 2023 13:10
Show Gist options
  • Save antoninhrlt/d60ca42565f6e0915e391b493f8bd008 to your computer and use it in GitHub Desktop.
Save antoninhrlt/d60ca42565f6e0915e391b493f8bd008 to your computer and use it in GitHub Desktop.
use std::any::Any;
pub trait ToAny {
fn as_any(&self) -> &dyn Any;
}
trait A: ToAny {
}
#[derive(Debug, Eq, PartialEq)]
struct B {
id: i32,
}
impl ToAny for B {
fn as_any(&self) -> &dyn Any {
self
}
}
impl A for B {
}
#[test]
fn a() {
let b = B {id: 1};
let boxed: Box<dyn A> = Box::new(b);
let b: &B = match boxed.as_any().downcast_ref::<B>() {
Some(b) => b,
None => panic!(),
};
assert_eq!(b, &B{id: 1});
}
#[test]
fn b() {
let boxeds: Vec<Box<dyn A>> = vec![
Box::new(B {id: 1}),
Box::new(B {id: 2}),
Box::new(B {id: 3}),
Box::new(B {id: 4}),
];
let mut values: Vec<&B> = vec![];
for boxed in &boxeds {
let found = match boxed.as_any().downcast_ref::<B>() {
Some(b) => b,
None => panic!(),
};
values.push(found);
}
assert_eq!(values, vec![
&B {id: 1},
&B {id: 2},
&B {id: 3},
&B {id: 4}
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment