Trait objects
Rust
trait Foo {
fn method(&self) -> String;
}
impl Foo for String {
fn method(&self) -> String { format!("string: {}", *self) }
}
fn main() {
let a: String = "foo".to_string();
let b: &Foo = &a;
b.method();
}
Compiled
pub struct TraitObject {
pub data: *mut (),
pub vtable: *mut (),
}
struct FooVtable {
destructor: fn(*mut ()),
size: usize,
align: usize,
method: fn(*const ()) -> String,
}
fn call_method_on_String(x: *const ()) -> String {
let string: &String = unsafe { &*(x as *const String) };
string.method()
}
static Foo_for_String_vtable: FooVtable = FooVtable {
destructor: ,
size: 24,
align: 8,
method: call_method_on_String as fn(*const ()) -> String,
};
fn main() {
let a: String = "foo".to_string();
let b = TraitObject {
data: &a,
vtable: &Foo_for_String_vtable
};
(b.vtable.method)(b.data);
}