Module lessons (2/2)
Methods, &self, &mut self and Self Constructors
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 theimplblocks. - Choose the method receiver correctly:
&self(read),&mut self(mutation) orself(consume). - Create conventional bound constructors (
fn new(...) -> Self) callable withType::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
- 11. The three receivers:
&self,&mut selfandself - 22. Associated functions (
Self::new) and encapsulation - 33. Automatic Referencing & Dereferencing
- 44. Multiple
implblocks and Builder patterns - 5Practical exercises
- 6Check for understanding
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.