Skip to content

Instantly share code, notes, and snippets.

@nyinyithann
Last active March 11, 2019 07:18
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 nyinyithann/c004081dae4c37b54cead95055809e86 to your computer and use it in GitHub Desktop.
Save nyinyithann/c004081dae4c37b54cead95055809e86 to your computer and use it in GitHub Desktop.
Convert Box<Trait> To concrete type with unsafe
trait Animal {
fn speak(&self);
}
#[derive(Debug)]
struct Dog {
name: String,
age: u8,
}
impl Animal for Dog {
fn speak(&self) {
println!("wuf..wuf...");
}
}
fn main() {
let animal: Box<dyn Animal> = Box::new(Dog {
name: "BigEyes".to_owned(),
age: 2,
});
let ptr = Box::into_raw(animal) as *mut (*mut (), *mut ());
let dog: &Dog = unsafe { std::mem::transmute(ptr) };
dbg!(dog);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment