liveBook · Manning

Impl block

As explained in Learn Rust in a Month of Lunches

An impl block is Rust syntax that defines methods or trait implementations associated with a type.

An `impl` block gives a struct or enum functions related to it. Write `impl` followed by the type name, then put the functions inside `{}`. It is a common next step after defining your own type. section 4.1.5 section 4.4

The functions inside can work in two ways:

  • A method takes `self` in some form. Use `&self` to work with a reference, or `&mut self` when the method needs to change the value. Call it with a dot, as in `my_mood.check()`. section 4.1.5 section 4.4
  • An associated function does not take `self`. Call it through the type with `::`, as in `Animal::new_cat()`. Such functions often create a new value. section 4.1.5
enum Mood {
    Good,
    Bad,
    Sleepy,
}
 
impl Mood {
    fn check(&self) {
        match self {
            Mood::Good => println!("Feeling good!"),
            Mood::Bad => println!("Eh, not feeling so good"),
            Mood::Sleepy => println!("Need sleep NOW"),
        }
    }
}
 
fn main() {
    let my_mood = Mood::Sleepy;
    my_mood.check();
}

Here, `impl Mood` adds `check` to an enum. The method looks at the value through `&self`, matches its variant, and prints a message. `my_mood.check()` calls it. section 4.1.5

`Self` with a capital S means the type being implemented; lowercase `self` means the particular value a method is called on. The dot operator also handles dereferencing references when calling methods, so you usually do not need to write extra `*` and `&` just to make a call. section 4.1.5 section 4.3

An `impl` block can also give a type a trait’s behavior. The form `impl Trait for Type` can use a trait’s provided methods or supply its own implementation. Some traits, such as `Debug`, can instead be added with `#[derive(Debug)]`; behavior Rust cannot guess must be implemented manually. section 7.1

impl<T: Copy> Cell<T> {
    pub fn get(&self) -> T {
        // Function details...
    }
 
    pub fn update<F>(&self, f: F) -> T
    where
        F: FnOnce(T) -> T,
    {
        // Function details...
    }
}

A later pattern places methods in a separate `impl<T: Copy> Cell<T>` block. The `Copy` requirement means those methods are available only when the inner type implements `Copy`. section 13.1.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines both kinds of functions, walks through enum methods, and later shows trait and Copy-bounded implementations without detailing their internals.
Examples
Shows an enum checked with a method, an animal changed through mutable methods, trait behavior, and Copy-restricted Cell methods.
What it assumes
Starts after defining structs and enums, explains method terminology, and builds toward uses involving references, traits, and generic bounds.
What you can do after
Build it from scratch: add methods and constructors to a type, then manually implement a trait when its behavior needs defining.
How it connects
Connects impl blocks to structs, enums, methods, associated functions, references, traits, and generic bounds.

Also explained in

Compare how 3 books explain impl block →

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.