liveBook · Manning

Type signature

As explained in Learn Rust in a Month of Lunches

A function signature is the declaration-level specification of a function's parameters and return type, including the corresponding specification for a method.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines signatures, contrasts default methods with declarations, and traces mismatches through compiler feedback.
Examples
Uses DogLike and Animal methods, Parrot behavior, and Cat's Display implementation as concrete signature examples.
What you can do after
Apply it by declaring trait methods, implementing matching signatures, and correcting return-type errors reported by the compiler.
How it connects
Connects function signatures with traits, method implementations, default methods, Display, and compiler type errors.

Also explained in

Compare how 8 books explain type signature →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.