Since Rust doesn't support upcasting, I'm trying to do the as_any
trick mentioned here, but with a parameterized type. However, when I try to call downcast_ref
on the returned Any, I get None
. Since I cannot print Any
to find out what it actually is:
`dyn std::any::Any` doesn't implement `std::fmt::Display`
`dyn std::any::Any` cannot be formatted with the default formatter
How can I debug what it actually is? Here is the failing code (playground):
use std::any::Any;
use std::rc::{Rc, Weak};
pub trait Wrapper: Any {
fn as_any(&self) -> &dyn Any;
}
pub struct WeakWrapper<T: Any> {
item: Weak<T>,
}
impl<'a, T: Any + 'static> Wrapper for WeakWrapper<T> {
fn as_any(&self) -> &dyn Any {
self
}
}
fn main() {
let rc = Rc::new(Box::new(5));
let weak_wrapper = WeakWrapper {
item: Rc::downgrade(&rc),
};
let item = weak_wrapper
.as_any()
.downcast_ref::<WeakWrapper<i32>>()
.map(|w| w.item.upgrade().map(|n| *n))
.flatten();
println!("Item is {}", item.unwrap());
}