Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::{any::Any, fmt};
- pub struct DebugAny {
- any: Box<dyn Any>,
- my_debug_impl: fn(&dyn Any, &mut fmt::Formatter) -> fmt::Result
- }
- impl DebugAny {
- pub fn from_debug<V: Any + fmt::Debug>(v: V) -> Self {
- // I'll just make the damn vtable *myself*!
- let my_debug_impl = |any: &dyn Any, f: &mut fmt::Formatter| {
- let v = any.downcast_ref::<V>().expect("debug vtable busted!");
- v.fmt(f)
- };
- Self {
- any: Box::new(v),
- my_debug_impl,
- }
- }
- pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
- self.any.downcast_ref::<T>()
- }
- }
- impl fmt::Debug for DebugAny {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- (self.my_debug_impl)(self.any.as_ref(), f)
- }
- }
- fn main() {
- let foo = "I'm a string!";
- let any = DebugAny::from_debug(foo);
- println!("debug: {:?}", any);
- println!("downcast_ref: {:?}", any.downcast_ref::<&str>())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement