Last active
March 11, 2019 07:18
-
-
Save nyinyithann/c004081dae4c37b54cead95055809e86 to your computer and use it in GitHub Desktop.
Convert Box<Trait> To concrete type with unsafe
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 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