trait对象 (trait object)
trait对象在Rust中是指使用指针封装了的 trait,比如 &SomeTrait 和 Box<SomeTrait>。
1. trait Foo { fn method(&self) -> String; }
3. impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } }
4. impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } }
6. fn do_something(x: &Foo) {
7. x.method();
8. }
10. fn main() {
11. let x = "Hello".to_string();
12. do_something(&x);
13. let y = 8u8;
14. do_something(&y);
15. }
x: &Foo其中x是一个trait对象,这里用指针是因为x可以是任意实现Foo的类型实例,内存大小并不确定,但指针的大小是固定的。
trait对象的实现
&SomeTrait 类型和普通的指针类型&i32不同。它不仅包括指向真实对象的指针,还包括一个指向虚函数表的指针。它的内部实现定义在在std::raw模块中:
1. pub struct TraitObject {
2. pub data: *mut (),
3. pub vtable: *mut (),
4. }
其中data是一个指向实际类型实例的指针, vtable是一个指向实际类型对于该trait的实现的虚函数表:
Foo的虚函数表类型:
1. struct FooVtable {
2. destructor: fn(*mut ()),
3. size: usize,
4. align: usize,
5. method: fn(*const ()) -> String,
6. }
之前的代码可以解读为:
1. // u8:
2. // 这个函数只会被指向u8的指针调用
3. fn call_method_on_u8(x: *const ()) -> String {
4. let byte: &u8 = unsafe { &*(x as *const u8) };
6. byte.method()
7. }
9. static Foo_for_u8_vtable: FooVtable = FooVtable {
10. destructor: /* compiler magic */,
11. size: 1,
12. align: 1,
14. method: call_method_on_u8 as fn(*const ()) -> String,
15. };
18. // String:
19. // 这个函数只会被指向String的指针调用
20. fn call_method_on_String(x: *const ()) -> String {
21. let string: &String = unsafe { &*(x as *const String) };
23. string.method()
24. }
26. static Foo_for_String_vtable: FooVtable = FooVtable {
27. destructor: /* compiler magic */,
28. size: 24,
29. align: 8,
31. method: call_method_on_String as fn(*const ()) -> String,
32. };
35. let a: String = "foo".to_string();
36. let x: u8 = 1;
38. // let b: &Foo = &a;
39. let b = TraitObject {
40. // data存储实际值的引用
41. data: &a,
42. // vtable存储实际类型实现Foo的方法
43. vtable: &Foo_for_String_vtable
44. };
46. // let y: &Foo = x;
47. let y = TraitObject {
48. data: &x,
49. vtable: &Foo_for_u8_vtable
50. };
52. // b.method();
53. (b.vtable.method)(b.data);
55. // y.method();
56. (y.vtable.method)(y.data);
对象安全
并不是所有的trait都能作为trait对象使用的,比如:
1. let v = vec![1, 2, 3];
2. let o = &v as &Clone;
会有一个错误:
1. error: cannot convert to a trait object because trait `core::clone::Clone` is not object-safe [E0038]
2. let o = &v as &Clone;
3. ^~
4. note: the trait cannot require that `Self : Sized`
5. let o = &v as &Clone;
6. ^~
让我来分析一下错误的原因:
1. pub trait Clone: Sized {
2. fn clone(&self) -> Self;
4. fn clone_from(&mut self, source: &Self) { ... }
5. }
虽然Clone本身集成了Sized这个trait,但是它的方法fn clone(&self) -> Self和fn clone_from(&mut self, source: &Self) { ... }含有Self类型,而在使用trait对象方法的时候Rust是动态派发的,我们根本不知道这个trait对象的实际类型,它可以是任何一个实现了该trait的类型的值,所以Self在这里的大小不是Self: Sized的,这样的情况在Rust中被称为object-unsafe或者not object-safe,这样的trait是不能成为trait对象的。
总结:
如果一个trait方法是object safe的,它需要满足:
- 方法有
Self: Sized约束, 或者 - 同时满足以下所有条件:
- 没有泛型参数
- 不是静态函数
- 除了
self之外的其它参数和返回值不能使用Self类型
如果一个trait是object-safe的,它需要满足:
- 所有的方法都是
object-safe的,并且 - trait 不要求
Self: Sized约束
