Last active
May 28, 2022 18:56
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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