Skip to content

Instantly share code, notes, and snippets.

Created October 7, 2016 17:10
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 anonymous/02a3ef9987b9c3a8dca1d5283122ef7a to your computer and use it in GitHub Desktop.
Save anonymous/02a3ef9987b9c3a8dca1d5283122ef7a to your computer and use it in GitHub Desktop.
Shared via Rust Playground
#![feature(raw)]
use std::raw::TraitObject;
use std::mem;
trait Foo {
fn f(&self);
}
struct Bar;
impl Foo for Bar {
fn f(&self) { println!("ok") }
}
fn erase<'a, T: ?Sized>(r: &'a T) -> TraitObject { unsafe { mem::transmute_copy(&r) } }
fn recover<'a, T: ?Sized>(r: TraitObject) -> &'a T { unsafe { mem::transmute_copy(&r) } }
fn erase_foo<'a>(r: &'a Foo) -> TraitObject { unsafe { mem::transmute(r) } }
fn recover_foo<'a>(r: TraitObject) -> &'a Foo { unsafe { mem::transmute(r) } }
fn main() {
let r: &Foo = &Bar;
let x = erase(r);
let xf = erase_foo(r);
println!("{:?} {:?}", x.data, x.vtable);
println!("{:?} {:?}", xf.data, xf.vtable);
let y: &Foo = recover(x);
let yf = recover_foo(xf);
y.f();
yf.f();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment