A type signature is the declaration-level specification of a function or method: its name, parameters, and return type. In a trait, the signature states the behavior an implementation must match. For example, `fn run(&self)` takes a shared reference to the implementing value and returns nothing. section 7.1 section 7.1.1
Use signatures to decide what a trait provides and what each implementation must supply:
- Write a method body in the trait when implementations should behave the same way; this creates a default method. section 7.1.1
- Write only the signature, such as `fn bark(&self);`, when each implementing type needs its own behavior. section 7.1.1
- Keep the implementation's parameters and return type aligned with the signature. Returning `i32` from a method declared to return nothing produces a type error. section 7.1
A trait signature and its implementation
The `DogLike` trait can require both methods without defining their bodies: `trait DogLike { fn bark(&self); fn run(&self); }`. An `Animal` implementation then supplies matching `bark` and `run` methods. The same matching rule appears when implementing `Display` for `Cat`: `fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result` must use the required parameters and return type. section 7.1.1
struct Animal {
name: String,
}
trait DogLike {
fn bark(&self); #1
fn run(&self);
}
impl DogLike for Animal {
fn bark(&self) {
println!("{}, stop barking!!", self.name);
}
fn run(&self) {
println!("{} is running!", self.name);
}
}
fn main() {
let rover = Animal {
name: "Rover".to_string(),
};
rover.bark();
rover.run();
}
A compact runnable example shows trait method signatures followed by matching implementations and calls. section 7.1.1







