Copy // u8:
// 这个函数只会被指向u8的指针调用
fn call_method_on_u8(x: *const ()) -> String {
let byte: &u8 = unsafe { &*(x as *const u8) };
byte.method()
}
static Foo_for_u8_vtable: FooVtable = FooVtable {
destructor: /* compiler magic */,
size: 1,
align: 1,
method: call_method_on_u8 as fn(*const ()) -> String,
};
// String:
// 这个函数只会被指向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: /* compiler magic */,
size: 24,
align: 8,
method: call_method_on_String as fn(*const ()) -> String,
};
let a: String = "foo".to_string();
let x: u8 = 1;
// let b: &Foo = &a;
let b = TraitObject {
// data存储实际值的引用
data: &a,
// vtable存储实际类型实现Foo的方法
vtable: &Foo_for_String_vtable
};
// let y: &Foo = x;
let y = TraitObject {
data: &x,
vtable: &Foo_for_u8_vtable
};
// b.method();
(b.vtable.method)(b.data);
// y.method();
(y.vtable.method)(y.data);