Blog

Part 10 · Structs and Methods in Rust: self, &self and &mut self

A struct groups named values into one type of your own. This part shows how to define and build structs, how they sit in memory, and how to pick between self, &self and &mut self when you write methods.

A struct is a type you make yourself, by giving a name to a group of values. Methods are functions that belong to that type. Together they’re how most Rust programs model their data.

This part covers structs, tuple structs and newtypes, and methods. Most of all, it covers the choice every method makes: does it read the value, change it, or use it up? That choice is &self, &mut self or self, and it’s ownership and borrowing from Part 6 and Part 7 again, in a new place. Every program here was run on Rust 1.95, and its output is pasted from the run.

Try this first

Counter holds one number, and add adds one to it. Decide what this prints before you scroll down:

struct Counter {
    count: u32,
}

impl Counter {
    fn add(&mut self) {
        self.count += 1;
    }
}

fn main() {
    let c = Counter { count: 0 };
    c.add();
    println!("{}", c.count);
}

It doesn’t compile:

error[E0596]: cannot borrow `c` as mutable, as it is not declared as mutable
...
13 |     c.add();
   |     ^ cannot borrow as mutable

add says &mut self: it needs a mutable borrow of the counter it’s called on. c.add() quietly takes that borrow for you, as &mut c. But c wasn’t declared with mut, and Part 7 showed that you can only take &mut of a mut variable. The fix is one word: let mut c.

Defining a struct and making one

A struct definition lists its fields, each with a name and a type:

struct User {
    name: String,
    age: u32,
    active: bool,
}

fn main() {
    let mut ana = User {
        name: String::from("Ana"),
        age: 30,
        active: true,
    };
    println!("{} is {}, active: {}", ana.name, ana.age, ana.active);

    ana.age += 1;
    ana.name.push_str(" Lima");
    println!("{} is {} now", ana.name, ana.age);
}

It prints:

Ana is 30, active: true
Ana Lima is 31 now

Three things to notice:

  • You make a value, called an instance, by naming the struct and giving every field a value. The fields can come in any order.
  • You read and write a field with a dot: ana.age.
  • mut belongs to the variable, so it covers the whole struct. You can’t mark one field as changeable and another as fixed.

Leave out a field, and the build stops with E0063, “missing field active in initializer of User“. A struct value always has every field set.

Printing a struct with Debug

println!("{}", ana) doesn’t compile, because Rust doesn’t guess how your type should look to a user. For a quick look while you work, ask the compiler to write a Debug printout for you with #[derive(Debug)]. Then {:?} prints the struct on one line, and {:#?} spreads it over several:

#[derive(Debug)]
struct User {
    name: String,
    age: u32,
    active: bool,
}

fn main() {
    let ana = User {
        name: String::from("Ana"),
        age: 30,
        active: true,
    };
    println!("{ana:?}");
    println!("{ana:#?}");
    println!("{} {} {}", ana.name, ana.age, ana.active);
}

It prints:

User { name: "Ana", age: 30, active: true }
User {
    name: "Ana",
    age: 30,
    active: true,
}
Ana 30 true

The last line reads each field once. Without it, the compiler warns that the fields are never read, because it doesn’t count the derived Debug code as a use.

#[derive(...)] asks the compiler to write some standard code for your type. Part 6 used it for Copy and Clone. Part 14 explains traits, which is what Debug is, and shows how to write Display so that {} works too.

Struct update syntax, and the move inside it

Often you want a new value that’s mostly the same as an old one. ..other fills in every field you didn’t write from other:

#[derive(Debug)]
struct User {
    name: String,
    age: u32,
    active: bool,
}

fn main() {
    let ana = User {
        name: String::from("Ana"),
        age: 30,
        active: true,
    };
    let ben = User {
        name: String::from("Ben"),
        ..ana
    };
    println!("{ana:?}");
    println!("{ben:?}");
    println!("{} is {}, active: {}", ben.name, ben.age, ben.active);
}

It prints:

User { name: "Ana", age: 30, active: true }
User { name: "Ben", age: 30, active: true }
Ben is 30, active: true

..ana must come last. It isn’t a copy of ana. It’s a list of assignments, one per missing field: age: ana.age, active: ana.active. Here those fields are a u32 and a bool, both Copy, so ana keeps everything and stays usable.

Now let the update take the name instead. That’s an assignment of a String, and Part 6 showed what that does:

#[derive(Debug)]
struct User {
    name: String,
    age: u32,
    active: bool,
}

fn main() {
    let ana = User {
        name: String::from("Ana"),
        age: 30,
        active: true,
    };
    let older = User { age: 31, ..ana };
    println!("{older:?}");
    println!("{ana:?}");
}

It prints:

error[E0382]: borrow of partially moved value: `ana`
...
14 |     let older = User { age: 31, ..ana };
   |                 ----------------------- value partially moved here
15 |     println!("{older:?}");
16 |     println!("{ana:?}");
   |                ^^^ value borrowed here after partial move
   |
   = note: partial move occurs because `ana.name` has type `String`, which does not implement the `Copy` trait

“Partially moved” is the key phrase. ..ana moved ana.name into older. ana.age on its own would still compile, but ana as a whole has a hole where its name was, and Rust won’t let you use it. The worked example below shows the ways out.

What a struct looks like in memory

A struct has no hidden header and no pointer of its own. It’s its fields, side by side, in one block. When the variable lives on the stack, the whole block is on the stack. Only a field that owns heap memory, like a String, points somewhere else:

use std::mem::size_of;

struct User {
    name: String,
    age: u32,
    active: bool,
}

fn main() {
    let user = User {
        name: String::from("Ana"),
        age: 30,
        active: true,
    };
    println!("{} {} {}", user.name, user.age, user.active);
    let (s, n, b) = (size_of::<String>(), size_of::<u32>(), size_of::<bool>());
    println!("String {s} + u32 {n} + bool {b} = {}", s + n + b);
    println!("User takes {} bytes", size_of::<User>());
}

It prints, on a 64-bit machine:

Ana 30 true
String 24 + u32 4 + bool 1 = 29
User takes 32 bytes

The fields add up to 29 bytes, but User takes 32. The extra 3 are padding: unused bytes that round the size up to a multiple of 8. Then, in a list of Users side by side, every name pointer still starts at an address the processor can read quickly.

stack heap user: User, 32 bytes on a 64-bit machine name 24 bytes len 3 cap 3 ptr age 4 bytes 30 active 1 byte true padding 3 bytes unused A n a owned by user.name One possible order: Rust may reorder fields (Part 27 covers layout).

A struct is one block holding its fields. Only the String field reaches out to the heap. The other fields live inside the block.

Two things follow from the picture:

  • Moving a User copies 32 bytes, and the 3 bytes of “Ana” stay where they are on the heap. It’s the same move as Part 6, with a bigger stack part.
  • Rust doesn’t promise the order. The compiler may reorder fields to waste less padding. Part 27 covers layout and alignment.

Tuple structs, newtypes and unit structs

A tuple struct has fields with positions instead of names. You read them as .0, .1 and so on, the same as a tuple from Part 4:

#[derive(Debug, Clone, Copy)]
struct Rgb(u8, u8, u8);

fn main() {
    let orange = Rgb(255, 165, 0);
    println!("{orange:?}, red part {}", orange.0);
    println!("green {}, blue {}", orange.1, orange.2);
}

It prints:

Rgb(255, 165, 0), red part 255
green 165, blue 0

A tuple struct with one field is called a newtype. It wraps a value in a new name, and costs nothing at run time: a Meters(f64) is 8 bytes, the same as an f64. What you gain is that the compiler now tells two kinds of number apart:

struct Meters(f64);
struct Feet(f64);

fn climb(height: Meters) -> f64 {
    height.0
}

fn main() {
    let ladder = Feet(12.0);
    println!("{}", climb(ladder));
}

It prints:

error[E0308]: mismatched types
...
10 |     println!("{}", climb(ladder));
   |                    ----- ^^^^^^ expected `Meters`, found `Feet`

With plain f64 parameters, that bug would compile and give a wrong answer. With newtypes, mixing up feet and meters is a type error. The fix is a conversion that says what it does:

#[derive(Debug, Clone, Copy)]
struct Meters(f64);

#[derive(Debug, Clone, Copy)]
struct Feet(f64);

fn to_meters(f: Feet) -> Meters {
    Meters(f.0 * 0.3048)
}

fn main() {
    let ladder = Feet(12.0);
    let m = to_meters(ladder);
    println!("{ladder:?} is {:.2} meters", m.0);
    println!("Meters takes {} bytes", std::mem::size_of::<Meters>());
}

It prints:

Feet(12.0) is 3.66 meters
Meters takes 8 bytes

A unit struct has no fields at all: struct Done;. It takes 0 bytes. It’s useful when a type matters but there’s no data to hold, which you’ll meet with traits in Part 14.

Methods: impl blocks

A method is a function that belongs to a type. You write methods inside an impl block for that type. The first parameter of a method is self, the value the method was called on:

#[derive(Debug)]
struct Rect {
    width: u32,
    height: u32,
}

impl Rect {
    fn new(width: u32, height: u32) -> Self {
        Self { width, height }
    }

    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn can_hold(&self, other: &Rect) -> bool {
        self.width >= other.width && self.height >= other.height
    }

    fn scale(&mut self, factor: u32) {
        self.width *= factor;
        self.height *= factor;
    }

    fn into_size(self) -> (u32, u32) {
        (self.width, self.height)
    }
}

fn main() {
    let mut a = Rect::new(3, 4);
    let b = Rect::new(2, 2);
    println!("{a:?} has area {}", a.area());
    println!("a can hold b: {}", a.can_hold(&b));

    a.scale(10);
    println!("after scale: {a:?}, area {}", a.area());

    let (w, h) = a.into_size();
    println!("width {w}, height {h}");
}

It prints:

Rect { width: 3, height: 4 } has area 12
a can hold b: true
after scale: Rect { width: 30, height: 40 }, area 1200
width 30, height 40

Inside an impl block, Self with a capital S is another name for the type, here Rect. Self { width, height } uses field init shorthand: width, is short for width: width,, and it works when a variable has exactly the field’s name. Each function in the block picks one of four shapes:

  • &self borrows the value to read it. area and can_hold only look, so they take &self. It’s short for self: &Self.
  • &mut self borrows the value to change it. scale changes the fields, so it takes &mut self. That’s why a needed let mut.
  • self takes ownership. The value moves into the method, and the caller can’t use it afterwards. into_size hands back the two numbers and a is gone.
  • No self at all makes an associated function. It belongs to the type but isn’t called on a value, so you call it with ::, as in Rect::new(3, 4). String::from from Part 5 is one too. Rust has no constructors; new is just the usual name.

Names follow a habit worth copying: into_... takes self and turns the value into something else, while as_... and to_... borrow. String::into_bytes and String::as_str work this way.

Picking self, &self or &mut self

The rule is to ask for the least you need:

The method… Takes You call it on
only reads fields &self any value or & reference
changes fields &mut self a mut variable or a &mut reference
gives the value away or turns it into something else self a value you own and won’t need again
builds a value, or doesn’t need one no self the type: Type::name(...)

Pick too little and the compiler says so inside the method. Here reset changes a field, but it asked only to read:

struct Counter {
    count: u32,
}

impl Counter {
    fn reset(&self) {
        self.count = 0;
    }
}

fn main() {
    let c = Counter { count: 5 };
    c.reset();
    println!("{}", c.count);
}

It prints:

error[E0594]: cannot assign to `self.count`, which is behind a `&` reference
...
7 |         self.count = 0;
  |         ^^^^^^^^^^^^^^ `self` is a `&` reference, so it cannot be written to

Pick too much and nothing fails inside the method, but every caller pays. A method that takes &mut self when it only reads forces every caller to have a mut variable, and it can’t be called while anything else holds a & borrow (Part 7’s rule). A method that takes self when it only reads uses the value up on the first call. “Try this first” showed the first error, and the second worked example below shows the other.

The dot borrows for you

a.area() passes &a to area, even though you never wrote &. When you call a method with a dot, Rust looks at what the method takes and adds the & or &mut itself. This is called auto-referencing. The method call is short for the full function call:

struct Rect {
    width: u32,
    height: u32,
}

impl Rect {
    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn scale(&mut self, factor: u32) {
        self.width *= factor;
        self.height *= factor;
    }
}

fn main() {
    let mut r = Rect {
        width: 3,
        height: 4,
    };
    println!("{}", r.area());
    println!("{}", Rect::area(&r));

    r.scale(2);
    Rect::scale(&mut r, 2);

    let view = &r;
    println!("{}", view.area());
}

It prints:

12
12
192

r.area() and Rect::area(&r) are the same call. r.scale(2) is Rect::scale(&mut r, 2). It works the other way too. view is already a &Rect, and view.area() passes it straight through, without making a &&Rect. That’s why you almost never write & or * in front of a method call, and why the error in “Try this first” pointed at c: the hidden &mut c is where the borrow happened.

One more thing, for later: fields are private to the module that defines the struct. Inside one file that doesn’t matter. From another module you can only reach fields marked pub. Part 18 covers modules and pub.

Worked example: the struct update that moved a name

We have ana, we want an older copy, and we still need ana afterwards. User { age: 31, ..ana } gave us E0382 in the struct update section above. Go back to that error and read its note: line first. It names the exact field, ana.name, and the reason, String isn’t Copy. That tells you the fix has to deal with that one field. There are three honest choices:

#[derive(Debug, Clone)]
struct User {
    name: String,
    age: u32,
    active: bool,
}

fn main() {
    let ana = User {
        name: String::from("Ana"),
        age: 30,
        active: true,
    };

    let older = User {
        name: ana.name.clone(),
        age: 31,
        ..ana
    };
    println!("1. {older:?} and {ana:?}");

    let twin = User {
        age: 31,
        ..ana.clone()
    };
    println!("2. {twin:?} and {ana:?}");

    let moved = User { age: 31, ..ana };
    println!("3. {moved:?}, and ana still has {} {}", ana.age, ana.active);
}

It prints:

1. User { name: "Ana", age: 31, active: true } and User { name: "Ana", age: 30, active: true }
2. User { name: "Ana", age: 31, active: true } and User { name: "Ana", age: 30, active: true }
3. User { name: "Ana", age: 31, active: true }, and ana still has 30 true
  1. Clone the one field that would move. Now ..ana only copies age and active, so ana is whole.
  2. Clone the whole value with ..ana.clone(). This needs Clone in the derive, and it clones name too. It’s simpler to write, but it clones every field, even the ones you then replace.
  3. Let it move when you’re done with ana. You can still read the fields that didn’t move, ana.age and ana.active, but not ana as a whole.

Worked example: a method that used up its value

A Report collects lines and then turns into one finished string. Turning it into a string is a natural self method, because a finished report shouldn’t be added to:

struct Report {
    title: String,
    lines: Vec<String>,
}

impl Report {
    fn new(title: &str) -> Self {
        Self {
            title: title.to_string(),
            lines: Vec::new(),
        }
    }

    fn add(&mut self, line: &str) {
        self.lines.push(line.to_string());
    }

    fn line_count(&self) -> usize {
        self.lines.len()
    }

    fn finish(self) -> String {
        format!("{}\n- {}", self.title, self.lines.join("\n- "))
    }
}

fn main() {
    let mut report = Report::new("Monday");
    report.add("fixed the login bug");
    report.add("reviewed two pull requests");
    println!("{} lines so far", report.line_count());

    let text = report.finish();
    println!("{text}");
}

It prints:

2 lines so far
Monday
- fixed the login bug
- reviewed two pull requests

Each method takes the least it needs: line_count reads, add changes, and finish uses the report up. Now add one late line after finishing. To keep it short, this version builds the report without new:

struct Report {
    title: String,
    lines: Vec<String>,
}

impl Report {
    fn add(&mut self, line: &str) {
        self.lines.push(line.to_string());
    }

    fn finish(self) -> String {
        format!("{}\n- {}", self.title, self.lines.join("\n- "))
    }
}

fn main() {
    let mut report = Report {
        title: String::from("Monday"),
        lines: Vec::new(),
    };
    report.add("fixed the login bug");
    let text = report.finish();
    report.add("one more thing");
    println!("{text}");
}

It prints:

error[E0382]: borrow of moved value: `report`
...
22 |     let text = report.finish();
   |                       -------- `report` moved due to this method call
23 |     report.add("one more thing");
   |     ^^^^^^ value borrowed here after move
   |
note: `Report::finish` takes ownership of the receiver `self`, which moves `report`
  --> src/main.rs:11:15
   |
11 |     fn finish(self) -> String {
   |               ^^^^

It’s E0382 again, the same error as a move in let b = a. The receiver is the value before the dot. The note at the bottom names the method and points at its self, so you know the move happened in the signature, not in your line. Here the error is doing its job: the report really is finished. When you hit this error on a method that only reads, the fix is the opposite one: change its self to &self. Exercise 3 is that case.

Tips and traps

  • Making a variable mut because one method complained. E0596 on x.method() means the method takes &mut self. If it really changes the value, add mut. If it only reads, fix the method to take &self instead.
  • ..other moves. Struct update copies Copy fields and moves the rest. If other has a String or Vec field you didn’t write out, other is partially moved. Clone that field, or write it out.
  • Taking self for a getter. fn name(self) -> String compiles, but the first call uses the value up. Take &self and return &str or a clone. Part 9 shows how returning a reference out of &self works.
  • {} on your struct. You get E0277, “User doesn’t implement std::fmt::Display“. Use {:?} with #[derive(Debug)] while you work, and write Display (Part 14) for output a user will read.
  • Plain numbers for different units. Two f64 parameters for meters and feet are easy to swap. A newtype costs no bytes and turns the swap into a compile error.
  • “field is never read” warnings. A field you only print with {:?} counts as unused. Read the field somewhere real, or remove it if nothing needs it.

Each method asks for the least it needs: &self to read, &mut self to change, and self only to use the value up.

Exercises

Exercise 1. Without running it, decide whether this compiles. Point derives only Debug.

let p = Point { x: 1, y: 2 };
let q = Point { x: 5, ..p };
println!("{p:?} {q:?}");

Exercise 2. Write a newtype Celsius(f64) with an associated function boiling() that returns 100 degrees, and a method to_fahrenheit that returns an f64 (multiply by 1.8 and add 32). Print the boiling point in Fahrenheit.

Exercise 3. This program doesn’t compile. Fix it by changing one word in the impl block, and say why that’s the right word.

struct Book {
    title: String,
    pages: u32,
}

impl Book {
    fn describe(self) -> String {
        format!("{} ({} pages)", self.title, self.pages)
    }
}

fn main() {
    let book = Book {
        title: String::from("Dune"),
        pages: 412,
    };
    println!("{}", book.describe());
    println!("{}", book.describe());
}

It prints:

error[E0382]: use of moved value: `book`
Answers

1. It compiles. ..p fills in only y, an i32, which is Copy. The field x comes from the new value, so nothing moves out of p, and p is still whole:

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 1, y: 2 };
    let q = Point { x: 5, ..p };
    println!("{p:?} {q:?}");
    println!("p.x + q.y = {}", p.x + q.y);
}

It prints:

Point { x: 1, y: 2 } Point { x: 5, y: 2 }
p.x + q.y = 3

2. boiling has no self, so you call it as Celsius::boiling(). to_fahrenheit only reads, so it takes &self:

struct Celsius(f64);

impl Celsius {
    fn boiling() -> Self {
        Self(100.0)
    }

    fn to_fahrenheit(&self) -> f64 {
        self.0 * 1.8 + 32.0
    }
}

fn main() {
    let water = Celsius::boiling();
    println!("water boils at {} F", water.to_fahrenheit());
    println!("still have {} C", water.0);
}

It prints:

water boils at 212 F
still have 100 C

3. Change describe(self) to describe(&self). The method only reads the title and the page count, so it should borrow. format! only reads the fields it prints, so the body doesn’t change:

struct Book {
    title: String,
    pages: u32,
}

impl Book {
    fn describe(&self) -> String {
        format!("{} ({} pages)", self.title, self.pages)
    }
}

fn main() {
    let book = Book {
        title: String::from("Dune"),
        pages: 412,
    };
    println!("{}", book.describe());
    println!("{}", book.describe());
}

It prints:

Dune (412 pages)
Dune (412 pages)

What’s next

A struct holds several values at once. In Part 11, we’ll meet enums, which hold one of several possible shapes, and match, which makes you handle every one of them.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.