1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-07-06 14:35:36 +02:00

Add a slide introducing dyn Trait in Generics (#2108)

I've been thinking it'd be simpler to introduce `dyn Trait` via `&dyn
Trait` rather than waiting for the smart pointers section and `Box<dyn
Trait>`. This PR adds a slide to the Generics section that introduces
`&dyn Trait` and compares it to `&impl Trait`, juxtaposing
monomorphization and static dispatch against type-erasure and dynamic
dispatch. I've then updated the existing trait object slide to call back
to the earlier introduction, and call out that using `Box<dyn Trait>`
gives you an owned trait object rather than a borrowed one.
This commit is contained in:
Nicole L
2024-05-31 06:59:36 -07:00
committed by GitHub
parent 06264e8cc7
commit 59bf3bdcfb
3 changed files with 93 additions and 3 deletions

View File

@ -2,9 +2,11 @@
minutes: 10
---
# Trait Objects
# Owned Trait Objects
Trait objects allow for values of different types, for instance in a collection:
We previously saw how trait objects can be used with references, e.g `&dyn Pet`.
However, we can also use trait objects with smart pointers like `Box` to create
an owned trait object: `Box<dyn Pet>`.
```rust,editable
struct Dog {