1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-04-26 17:23:01 +02:00

Add speaker notes for trait objects (#194)

This commit is contained in:
Fabian Bornhofen 2023-01-23 21:11:53 +01:00 committed by GitHub
parent 5792806947
commit 55fbb23cca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -35,3 +35,20 @@ fn main() {
}
}
```
<details>
* Traits may specify pre-implemented (default) methods and methods that users are required to implement themselves. Methods with default implementations can rely on required methods.
* Types that implement a given trait may be of different sizes. This makes it impossible to have things like `Vec<Greet>` in the example above.
* `dyn Greet` is a way to tell the compiler about a dynamically sized type that implements `Greet`.
* In the example, `pets` holds Fat Pointers to objects that implement `Greet`. The Fat Pointer consist of two components, a pointer to the actual object and a pointer to the virtual method table for the `Greet` implementation of that particular object.
Compare these outputs in the above example:
```rust,ignore
println!("{} {}", std::mem::size_of::<Dog>(), std::mem::size_of::<Cat>());
println!("{} {}", std::mem::size_of::<&Dog>(), std::mem::size_of::<&Cat>());
println!("{}", std::mem::size_of::<&dyn Greet>());
println!("{}", std::mem::size_of::<Box<dyn Greet>>());
```
</details>