Curriculum Traits & generics impl Trait and trait objects
impl Trait and trait objects
Rust has two styles of polymorphism: static dispatch with generics or impl Trait, and dynamic dispatch with dyn Trait. This theme teaches when each is appropriate and why trait objects usually live behind a pointer such as &dyn Trait or Box<dyn Trait>. Planned exercises: 1. choose impl Trait for an argument. 2. recognise dyn Trait. 3. choose Box<dyn Trait> for heterogeneous owned values. 4. fill an impl Iterator return. 5. fill &dyn Display. 6. write a static dispatch helper. 7. write a trait-object collection. 8. translate TS interface polymorphism. 9. fix an attempt to return two concrete types from one impl Trait function.
Exercises
9 ready
01
pick one
A function accepts ANY value that implements Greeter. Pick
02
pick one
A function takes a BORROWED reference to ANY value that
03
pick one
A Vec stores a HETEROGENEOUS mix of values — different
04
fill blanks
Fill the keyword in the return type so this function returns
05
fill blanks
Fill the parameter type. The function takes a borrowed
06
write a program
Write a trait Greeter with greet(&self) -> String. Impl
07
write a program
Two structs (Robot, Cat) implement the SAME trait
08
write a program
Translate TS interface polymorphism. Trait Speaker,
09
write a program
This program fails because impl Trait in RETURN position