trait object
a reference to a trait type (or Box
two ways convert concrete type to trait object
- assigning to variable
1
2
3
4use std::io::Write;
let mut buffer: Vec<u8> = vec![];
let w: &mut dyn Write = &mut buffer; - pass a concrete type as a argument to a functionin both ways, buffer is converted to a trait object implements Write
1
2
3
4
5
6
7
8fn main() {
let mut buffer: Vec<u8> = vec![];
writer(&mut buffer);
}
fn writer(w: &mut dyn Write) {
// ...
}
in memory, a trait object (in the example, w) is a fat point consists two pointers
the vtable is generated once at compile time and shared by all objects of the same type. the vtable contains pointers to the machine code of the functions that must be present for a type to be a “Writer”