liveBook · Manning

Method

As explained in Learn Rust in a Month of Lunches

A method is a function associated with a type that is invoked through an instance or type and may receive the instance through self, &self, or &mut self.

A method is a function attached to a type. To give a struct or enum methods, write an `impl` block. A regular method takes `self` in some form and is usually called with a dot, as in `value.method()`. section 4.1.5

The form of `self` tells you how the method uses the value:

A function in an `impl` block that does not take `self` is an associated function. Call it through the type with `::`, as in `String::from()` or `Vec::new()`. Associated functions often create new values. `Self` with a capital S means the type; lowercase `self` means the particular value. section 4.1.5

#[derive(Debug)]
enum AnimalType {
    Cat,
    Dog,
}
 
#[derive(Debug)]
struct Animal {
    age: u8,
    animal_type: AnimalType,
}
 
impl Animal {
    fn new_cat() -> Self {                    #1
        Self {                                #2
            age: 10,
            animal_type: AnimalType::Cat,
        }
    }
 
    fn check_type(&self) {
        match self.animal_type {
            AnimalType::Dog => println!("The animal is a dog"),
            AnimalType::Cat => println!("The animal is a cat"),
        }
    }
 
    fn change_to_dog(&mut self) {             #3
        self.animal_type = AnimalType::Dog;
        println!("Changed animal to dog! Now it's {self:?}");
    }
 
    fn change_to_cat(&mut self) {
        self.animal_type = AnimalType::Cat;
        println!("Changed animal to cat! Now it's {self:?}");
    }
 
}
 
fn main() {
    let mut new_animal = Animal::new_cat();   #4
    new_animal.check_type();
    new_animal.change_to_dog();
    new_animal.check_type();
    new_animal.change_to_cat();
    new_animal.check_type();
}

This `impl Animal` block puts a constructor and two kinds of regular method together: `new_cat()` returns a new `Self`, `check_type(&self)` checks a value, and `change_to_dog(&mut self)` changes one. section 4.1.5

The dot is helpful when you have a reference. A `String` method such as `.is_empty()` can be called even on a `&&String`: Rust dereferences as needed to reach the type and supplies the reference the method needs. You usually do not have to write the `*` operators yourself for a method call. section 4.3

Methods can also come from traits. Implementing a trait for a type gives it the trait’s methods; the type can still have its own separate methods. section 7.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains impl blocks, three self forms, call syntax, and dot-operator dereferencing; defers special reasons to call self-taking methods with ::.
Examples
Uses an Animal impl block with checking and changing methods, plus a String method called through a double reference.
What it assumes
Assumes familiarity with structs, enums, and basic references while introducing impl blocks and self forms.
What you can do after
Build it from scratch: add methods to a struct or enum and choose &self or &mut self according to whether it changes.
How it connects
Connects methods to structs, enums, associated functions, references, the dot operator, and traits.

Also explained in

Compare how 20 books explain method →

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.