Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 132 ยท Structs, Enums and Traits Basics

Methods and Associated Functions

Learn Rust methods and associated functions - impl blocks, &self, &mut self and self, new constructors, method chaining, associated constants and the Self type.

A struct holds data. A method is a function that belongs to that data: instead of area(rect) you write rect.area(). Rust has no classes, but it gives you the same convenience with an impl block (short for implementation). Methods keep the code that works on a type next to the type, make call sites read naturally, and let you chain operations: text.trim().to_uppercase().

This lesson shows how to write impl blocks, the three ways a method can receive self (and what each means for ownership), associated functions such as new, method chaining, associated constants and the Self type. If you have not read Structs and References and Borrowing, do that first.

Your first impl block

Put methods for a type inside impl TypeName { ... }. The first parameter of a method is always some form of self, which stands for the value the method is called on:

Rust A method with &self

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

&self is shorthand for self: &Self, a shared reference to the value. The method can read the fields but not change them, and the caller keeps the value. r.area() is sugar for Rectangle::area(&r); Rust inserts the & for you (this is called automatic referencing), so you never write (&r).area().

The three kinds of self

Which form of self you choose decides what the method may do and what happens to the caller's value:

Receiver Meaning Caller afterwards
&self read-only borrow still has the value
&mut self exclusive borrow, can modify still has the value (changed)
self takes ownership value is moved and gone
Rust &self, &mut self and self side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The fill call needed let mut tank, because &mut self requires a mutable binding. The method drain takes self by value, which consumes the tank. Methods that consume the receiver are typically conversions or "finish" steps; the standard library names such methods into_... (into_bytes) or finish.

What happens if you use a value after a consuming method?

Rust Using a value after self was consumed (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports:

TEXT
error[E0382]: borrow of moved value: `tank`
  --> main.rs:15:20
   |
12 |     let tank = Tank { liters: 10 };
   |         ---- move occurs because `tank` has type `Tank`, which does not implement the `Copy` trait
13 |     let total = tank.drain();
   |                      ------- `tank` moved due to this method call
14 |     println!("{total}");
15 |     println!("{}", tank.liters);
   |                    ^^^^^^^^^^^ value borrowed here after move
   |
note: `Tank::drain` takes ownership of the receiver `self`, which moves `tank`

Notice that the error points at the method call and the note explains that drain takes ownership of self. The fix is to choose the receiver on purpose. If callers need the tank afterwards, make drain take &mut self and set the level to zero.

Default to &self. Use &mut self when the method changes the value. Use self only when the method turns the value into something else or must take ownership of it.

Calling mutating methods through references

A method call looks the same whether you hold the value, a reference to it or a Box of it. Rust automatically adds or removes &, &mut and * until the receiver matches (auto-referencing and auto-dereferencing):

Rust Calling methods through references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This is why Rust does not need C's -> operator. Inside bonus, score is a &mut Score, and score.add(100) just works.

Associated functions and constructors

An impl block can also hold functions without a self parameter. These are associated functions. They are called with :: on the type, not with a dot on a value. The most common one is a constructor named new:

Rust new and other associated functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

new is only a naming convention. Rust has no special constructor syntax and Player { ... } works anywhere the fields are visible. A new function earns its keep when it sets defaults, checks input, or when some fields are private. Sometimes construction can fail; then return Option<Self> or Result<Self, E> (see Option and Result), and name the function try_new or parse.

When a type has a natural "zero" value, implement the Default trait instead of (or besides) new(); Traits shows how.

Self and Self::

Inside an impl, Self is an alias for the type being implemented. It saves typing, and when you rename the type you only change one place. Use it as a return type (-> Self), in struct literals (Self { ... }) and for associated items (Self::new(...), Self::MAX_HEALTH).

Method chaining

A method that returns Self (or a reference to it) allows calls to be chained. There are two common styles:

Rust Chaining with self and with &mut self

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The consuming style creates the final value in a single expression, which is perfect for builders. The &mut Self style modifies a value you already hold. Pick one per type; mixing them is confusing.

Associated constants

An impl can also define constants that belong to the type:

Rust Associated constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You reach them with Circle::PI from outside or Self::PI from inside. Compare with module-level const items: an associated constant is namespaced under the type, which is better for values that only make sense together with it (u32::MAX is an associated constant).

Multiple impl blocks

A type may have any number of impl blocks. This is legal and common for organization: constructors in one block, a group of related methods in another, trait implementations in their own blocks:

Rust More than one impl block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Multiple blocks become important once generics enter the picture (Trait Bounds shows methods that exist only for some type arguments).

A method with the same name as a field

Fields and methods live in different namespaces: r.width is the field and r.width() is the method. Rust programmers use this on purpose for getters, which are named after the field without a get_ prefix:

Rust Getter named like the field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You only need getters when fields are private (typically inside a module), so that the type controls how it can be changed. Within a small program, public fields are fine.

Pitfalls and design notes

  • Forgetting mut. Calling a &mut self method on a non-mut binding fails with E0596. The compiler's help line tells you to write let mut.
  • Moving out of &self. A method that borrows self cannot return an owned field without cloning it: fn name(&self) -> String { self.name } fails with E0507. Return &str (a view) or .clone() (an owned copy).
  • Method vs function. If the function does not need to be called with dot syntax and is not conceptually "of" one type, a free function is fine. Rust code mixes both.
  • No overloading. You cannot define two methods with the same name and different parameters. Use different names (new, with_health), generics, or traits.
  • Performance. A method call is a normal function call, and the optimizer inlines small ones; methods cost nothing extra compared with free functions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fn area(&self) -> f64 mean?

    &self is short for self: &Self. The method reads through a shared reference, so the caller can keep using the value.
  2. 2. Which line calls an associated function (no self)?

    Associated functions are called with :: on the type. Methods with a self receiver are called with a dot on a value.
  3. 3. After let total = tank.drain(); where drain takes self by value, what happens when you use tank again?

    A method taking self consumes the receiver. Using the moved value gives E0382 unless the type is Copy.
  4. 4. Why can you write score.add(100) when score is a &mut Score, without writing (*score).add(100)?

    Method calls use automatic referencing and dereferencing, so the receiver is adjusted to match the method's self type.
  5. 5. What is Self inside an impl block?

    Self (capital S) is a type alias for the type of the impl block; lowercase self is the receiver value.

Summary

  • Methods live in impl blocks and take self as their first parameter; r.area() is sugar for Rectangle::area(&r).
  • Choose the receiver deliberately: &self to read, &mut self to modify, self to consume.
  • Associated functions have no self and are called with Type::name(); new is a convention, not syntax.
  • Self is the implementing type; lowercase self is the value.
  • Return Self (consuming style) or &mut Self (borrowing style) to enable chaining.
  • Associated constants and multiple impl blocks organize related items.
  • Rust automatically references and dereferences method receivers.

Next: Enums