Skip to content

Instantly share code, notes, and snippets.

@gary17
Last active May 28, 2022 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gary17/0e63e7a041fe706e70bcc8eb3f55d3ad to your computer and use it in GitHub Desktop.
Save gary17/0e63e7a041fe706e70bcc8eb3f55d3ad to your computer and use it in GitHub Desktop.
Downcasting from a trait object to a generic struct that implements the trait.
trait A {
fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
}
struct B<T> {
_unused: T
}
impl<T: 'static> A for B<T> { // static, else: "the parameter type `T` may not live long enough"
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
let mut inst = Box::new(B{_unused: true});
let virt: &mut dyn A = &mut (*inst);
let _cast = virt.as_any_mut().downcast_mut::<B<bool>>().unwrap();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment