Traits: shared behavior
A trait describes a behavior that several types can have in common: "everything that can be drawn", "everything that can be compared", "everything that can be turned into text". It is similar to an interface in Java or C#, although with differences you will see in this lesson. Traits are the foundation of almost the whole standard library: println! uses Display and Debug, == uses PartialEq, and for loops use Iterator. Understanding them unlocks the rest of the language.
Defining and implementing a trait
It is declared with trait and a list of method signatures. Each type implements it with impl Trait for Type. A trait can offer a default implementation for some methods, which types can use as is or override. An important detail, called the orphan rule: you can only implement a trait for a type if your crate defines the trait or defines the type. You cannot implement Display for Vec<i32>, because neither is yours.
trait Animal {
fn name(&self) -> String;
fn sound(&self) -> String;
// default implementation
fn speak(&self) -> String {
format!("{} says {}", self.name(), self.sound())
}
}
struct Dog;
struct Cat {
lives: u8,
}
impl Animal for Dog {
fn name(&self) -> String { String::from("Dog") }
fn sound(&self) -> String { String::from("woof") }
}
impl Animal for Cat {
fn name(&self) -> String { format!("Cat ({} lives)", self.lives) }
fn sound(&self) -> String { String::from("meow") }
fn speak(&self) -> String { format!("{} purrs", self.name()) } // override
}
fn main() {
println!("{}", Dog.speak());
println!("{}", Cat { lives: 9 }.speak());
}Traits as parameters
There are two ways to say "I accept any type that implements this trait". The impl Trait syntax in parameters (fn show(a: &impl Animal)) is the shortest. The trait bound syntax (fn show<T: Animal>(a: &T)), which appears in the next lesson about generics, is equivalent and more flexible. In both cases the compiler generates specific code for each concrete type (static dispatch), at no runtime cost. You can require several traits at once with +, for example T: Animal + Debug.
use std::fmt;
trait Describe {
fn describe(&self) -> String;
}
struct Point { x: i32, y: i32 }
impl Describe for Point {
fn describe(&self) -> String { format!("point at {}, {}", self.x, self.y) }
}
impl Describe for i32 {
fn describe(&self) -> String { format!("the number {}", self) }
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn print_it(item: &impl Describe) {
println!("{}", item.describe());
}
fn print_both<T: Describe + fmt::Display>(item: &T) {
println!("{} / {}", item, item.describe());
}
fn main() {
print_it(&42);
print_it(&Point { x: 1, y: 2 });
print_both(&Point { x: 3, y: 4 });
}Trait objects: dyn Trait
Sometimes you need to store values of different types in the same collection, for example a list of varied animals. A Vec<T> requires a single T, so you use a trait object: Vec<Box<dyn Animal>>. Box puts each value on the heap, and dyn means "some type that implements Animal, decided at runtime" (dynamic dispatch). The cost is a small indirection when calling methods. Use it when you need to mix types; if they are all the same or you know them at compile time, prefer generics.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
struct Circle(f64);
impl Shape for Square {
fn area(&self) -> f64 { self.0 * self.0 }
}
impl Shape for Circle {
fn area(&self) -> f64 { 3.14159 * self.0 * self.0 }
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0)), Box::new(Circle(1.0))];
let total: f64 = shapes.iter().map(|s| s.area()).sum();
println!("total area = {:.2}", total);
}One last point: traits also let you return types without naming them using impl Trait in the return position, widely used with iterators and closures, which you will see in week 7. And the most important traits of the standard library deserve to be known by name: Display to show to the user, Debug for debugging, Clone to duplicate, Default for the initial value, From and Into to convert and Drop to run code when a value is freed. When you design your types, implementing these traits makes your data fit the rest of the ecosystem effortlessly.
trait Greeter {
fn greet(&self) -> String;
fn shout(&self) -> String {
self.greet().to_uppercase()
}
}
struct English { name: String }
struct Spanish { name: String }
impl Greeter for English {
fn greet(&self) -> String { format!("Hello, {}!", self.name) }
}
impl Greeter for Spanish {
fn greet(&self) -> String { format!("Hola, {}!", self.name) }
}
fn main() {
let all: Vec<Box<dyn Greeter>> = vec![
Box::new(English { name: String::from("Ana") }),
Box::new(Spanish { name: String::from("Luis") }),
];
for g in &all {
println!("{} / {}", g.greet(), g.shout());
}
}Testez vos acquis
Question 1 sur 4What is a trait?
✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères