0Pricing
Learn Rust Coding · Lesson

Default Methods

Trait defaults.

Methods With a Body

Trait methods do not have to be just signatures. A trait can provide a default implementation — a method body that implementors get automatically.

This reduces boilerplate across many types.

A Default Method

Write the body right inside the trait. Types that implement the trait inherit it for free, with no extra code.

trait Greet {
    fn hello(&self) -> String {
        String::from("Hello there")
    }
}

struct Robot;
impl Greet for Robot {}

fn main() {
    println!("{}", Robot.hello());
}

All lessons in this course

  1. Defining Traits
  2. Trait Objects and dyn
  3. Static vs Dynamic Dispatch
  4. Default Methods
← Back to Learn Rust Coding