Lesson 1 · Unit 07
Traits
A promise a type makes, default methods, Display and the derives
What you practise
- A trait,
impl Trait for Type, default methods,Display, the derives and what they write for you
Try a question from this lesson
Pick one
struct Dog; is a struct with no fields. Both types have a method that speaks. Which line does the compiler reject?
struct Dog;
struct Cat;
impl Dog {
fn speak(&self) -> &str { "Woof" }
}
impl Cat {
fn speak(&self) -> &str { "Meow" }
}
fn greet(d: &Dog) {
println!("{}!", d.speak());
}
greet(&Dog);
greet(&Cat);Hint
Look at the type the function asks for, then at what each call hands it.
Correct answer
Line 13
Why
The function asks for a &Dog, and a Cat is a different type, however alike the two look: expected &Dog, found &Cat. What the function really needs is "anything that can speak". A trait lets you say that.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A trait is a promise
A trait names something types can do. It lists methods without bodies. Any type that wants to carry the trait must provide them.
impl Speak for Cat is where Cat keeps the promise. From then on, a Cat counts as something that can speak.
trait Speak {
fn speak(&self) -> &str;
}
struct Cat;
impl Speak for Cat {
fn speak(&self) -> &str { "Meow" }
}
println!("{}", Cat.speak());Concept
A function for anything that speaks
A parameter of type &impl Speak accepts a borrow of any type that carries the Speak trait.
Inside the function you may call the trait's methods and nothing else: that is all the function knows about the value. One function now serves cats, dogs and every type written later.
trait Speak {
fn speak(&self) -> &str;
}
struct Cat;
struct Dog;
impl Speak for Cat {
fn speak(&self) -> &str { "Meow" }
}
impl Speak for Dog {
fn speak(&self) -> &str { "Woof" }
}
fn greet(who: &impl Speak) {
println!("{}!", who.speak());
}
greet(&Cat);
greet(&Dog);Concept
Default methods
A trait method can come with a body. That body is the default: every type that carries the trait gets the method for free, and may replace it with its own.
A default method can call the trait's other methods. Here one required method, price, powers a free one, tax.
trait Priced {
fn price(&self) -> i32;
fn tax(&self) -> i32 {
self.price() / 10
}
}
struct Toy;
impl Priced for Toy {
fn price(&self) -> i32 { 50 }
}
println!("{}", Toy.tax());9 more exercises in the app
- 1× fill the blanks
- 2× multiple choice
- 3× type the answer
- 1× true or false
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.