Skip to main content
Module 4 · Lesson 2 of 28/24 in the course~18 min
Module lessons (2/2)

Methods, &self, &mut self and Self Constructors

Lesson preview5 hands-on exercises readyCourse Rust · Module 4 — Structures and Methods

impl blocks, difference between &self, &mut self and self by value, associated functions Self::new() and encapsulation with pub.

What you'll learn in this lesson

  • Separate the data schema (struct) from the behavior across the impl blocks.
  • Choose the method receiver correctly: &self (read), &mut self (mutation) or self (consume).
  • Create conventional bound constructors (fn new(...) -> Self) callable with Type::new(...).

Overview

Rust clearly separates the structure of the data from the methods that operate on it: the data lives inside struct, while the methods and associated functions reside inside one or more impl NomeStruct { ... } blocks.

The first parameter of a method establishes what access it has to the calling instance:

Sections covered in this lesson

  1. 11. The three receivers: &self, &mut self and self
  2. 22. Associated functions (Self::new) and encapsulation
  3. 33. Automatic Referencing & Dereferencing
  4. 44. Multiple impl blocks and Builder patterns
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 4 — Structures and Methods

Unlock "Methods, &self, &mut self and Self Constructors" and the full Course Rust curriculum

`impl` blocks, difference between `&self`, `&mut self` and `self` by value, associated functions `Self::new()` and encapsulation with `pub`.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Rust plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.