Implementing Traits
// Copyright 2024 Google LLC
// SPDX-License-Identifier: Apache-2.0
trait Pet {
fn talk(&self) -> String;
fn greet(&self) {
println!("Oh you're a cutie! What's your name? {}", self.talk());
}
}
struct Dog {
name: String,
age: i8,
}
impl Pet for Dog {
fn talk(&self) -> String {
format!("Woof, my name is {}!", self.name)
}
}
fn main() {
let fido = Dog { name: String::from("Fido"), age: 5 };
dbg!(fido.talk());
fido.greet();
}
-
To implement
TraitforType, you use animpl Trait for Type { .. }block. -
Unlike Go interfaces, just having matching methods is not enough: a
Cattype with atalk()method would not automatically satisfyPetunless it is in animpl Petblock. -
Traits may provide default implementations of some methods. Default implementations can rely on all the methods of the trait. In this case,
greetis provided, and relies ontalk. -
Multiple
implblocks are allowed for a given type. This includes both inherentimplblocks and traitimplblocks. Likewise multiple traits can be implemented for a given type (and often types implement many traits!).implblocks can even be spread across multiple modules/files.