CodeBlanks Logo Icon CodeBlanks

&mut self

Define methods that mutate the struct with &mut self.

&mut self

Methods that change the instance's fields take &mut self. Such a method can only be called on a mut variable:

struct Sayac { deger: u32, adim: u32 }

impl Sayac {
    fn artir(&mut self) {
        self.deger += self.adim;
    }
    fn sifirla(&mut self) {
        self.deger = 0;
    }
}

Writing let s = Sayac { .. }; s.artir(); is error E0596: "cannot borrow as mutable".

Chaining

If a &mut self method returns &mut Self, calls can be chained:

impl Sayac {
    fn ekle(&mut self, n: u32) -> &mut Self {
        self.deger += n;
        self
    }
}

let mut s = Sayac { deger: 0, adim: 1 };
s.ekle(2).ekle(3);
println!("{}", s.deger);   // 5

This pattern is common in configuration objects (builders).

Practice Step counter

For Sayac { deger: u32, adim: u32 }, write fn artir(&mut self) (deger += adim) and fn sifirla(&mut self). Start with deger: 0, adim: 5, increment twice and record the value; then reset and record it again (print on one line, separated by a space).

Starter code

main.rs
struct Sayac {
    deger: u32,
    adim: u32,
}

fn main() {
    // buraya yaz
}

Sample solution

main.rs
struct Sayac {
    deger: u32,
    adim: u32,
}

impl Sayac {
    fn artir(&mut self) {
        self.deger += self.adim;
    }
    fn sifirla(&mut self) {
        self.deger = 0;
    }
}

fn main() {
    let mut s = Sayac { deger: 0, adim: 5 };
    s.artir();
    s.artir();
    let once = s.deger;
    s.sifirla();
    println!("{} {}", once, s.deger);
}

Expected output

10 0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if another <code>&amp;s</code> reference is alive while calling a method that takes <code>&amp;mut self</code>?

  • Runtime panic
  • The reference is copied automatically
  • Compile error: a reader and a writer can't coexist Correct answer
  • No problem

Explanation: A method call is a borrow too; the borrowing rules apply just the same.

2 A modifying method

Question
fn sifirla(____) {
    self.deger = 0;
}
Answer
fn sifirla(&mut self) {
    self.deger = 0;
}

Explanation: Changing a field requires a mutable borrow.

3 Code and result

Term Meaning
let s; s.artir() E0596
let mut s; s.artir() Works
-> &mut Self Chaining
self.deger = 0 Field assignment

All lessons in Beginner