Skip to content
RustLearn

Module 06 — Structs & Methods

Goal

Model your domain with structs, attach behavior with impl, and learn the difference between methods, associated functions and constructors.

Start here — what this module is really about

So far your programs have juggled loose values: a width, a height, a name, an age. This module is about giving a shape to data that belongs together, and then attaching behaviour to that shape.

A struct is a named group of named fields. That is all it is:

rust
struct Rectangle {
    width: u32,
    height: u32,
}

Two things this buys you immediately. First, Rectangle is now a type — a function that expects a Rectangle cannot be handed a Circle, even if both are two numbers underneath, so a whole class of mix-up becomes impossible. Second, the fields have names, so rect.width reads as what it is instead of dimensions.0.

Then comes the part that surprises people arriving from Java or Python: the data and its behaviour are declared separately. Fields go in the struct; methods go in a separate impl block. There is no constructor keyword either — a "constructor" in Rust is just a plain function, conventionally called new, that returns an instance.

The other thing to watch for, and it is a direct consequence of module 04: every method starts by declaring what it wants from self.

  • &self — I only need to read this. Almost all methods.
  • &mut self — I am going to change it.
  • self — I consume it; the caller does not get it back.

That one character in front of self is the same ownership decision you met in module 04, now applied to methods.

The one sentence to remember: a struct names a shape, an impl block gives it behaviour, and every method declares up front whether it reads, changes, or consumes the value.

Learning objectives

  • Define classic, tuple, and unit structs
  • Write impl blocks with methods and associated functions
  • Choose correctly between self, &self, and &mut self
  • Use #[derive] for common behaviour
  • Apply the builder and newtype patterns

6.1 Defining and instantiating

rust
#[derive(Debug)]
struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {
    let mut user = User {
        username: String::from("ferris"),
        email: String::from("ferris@rust-lang.org"),
        sign_in_count: 1,
        active: true,
    };

    user.email = String::from("new@example.com");   // requires `mut` on the binding
    println!("{user:?}");
}

Notes:

  • Field order at construction doesn't matter, but every field must be given a value. There are no optional fields and no undefined.
  • Mutability is per-binding, not per-field. You cannot have one mutable field in an otherwise immutable struct.
  • Naming: PascalCase for the type, snake_case for fields.

Field init shorthand

rust
fn build_user(username: String, email: String) -> User {
    User {
        username,          // shorthand for username: username
        email,
        sign_in_count: 1,
        active: true,
    }
}

Struct update syntax

rust
let user2 = User {
    email: String::from("other@example.com"),
    ..user                 // take remaining fields from `user`
};

Gotcha

..user moves non-Copy fields out of user. After the code above, user.username is moved and user is partially moved — you can't use it as a whole any more. Use ..user.clone() if you need to keep the original.

Tuple structs

rust
struct Color(u8, u8, u8);
struct Point(f64, f64);

let black = Color(0, 0, 0);
let origin = Point(0.0, 0.0);
println!("{} {}", black.0, origin.1);

Use when field names would be noise. Color and Point are distinct types even though both are three/two numbers — that's the point.

Unit-like structs

rust
struct AlwaysEqual;
let subject = AlwaysEqual;

Zero bytes. Useful as a marker type or when implementing a trait with no data.

The newtype pattern

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

fn walk(distance: Meters) { /* ... */ }

// walk(Feet(10.0));   // ❌ type error — units can't be confused
walk(Meters(10.0));    // ✅

A zero-cost wrapper that makes illegal states unrepresentable. Use it for IDs (struct UserId(u64)), units, and validated values (struct Email(String) with a private field and a checked constructor).


Analogy — the form and the filled-in form

A struct definition is a blank form printed by your organisation: these fields, these types, in this order. An instance is one filled-in copy sitting in a drawer. The value of naming the form is that a Rectangle can never be quietly handed to something expecting a Circle, no matter how similar the numbers on the page look.

6.2 Methods and impl

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

impl Rectangle {
    // Associated function (no self) — like a static method / constructor
    fn new(width: u32, height: u32) -> Self {
        Self { width, height }
    }

    fn square(size: u32) -> Self {
        Self { width: size, height: size }
    }

    // &self: read-only borrow
    fn area(&self) -> u32 {
        self.width * self.height
    }

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

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

    // self: consumes the value
    fn into_square(self) -> Rectangle {
        let s = self.width.max(self.height);
        Rectangle { width: s, height: s }
    }
}

fn main() {
    let mut r = Rectangle::new(30, 50);      // :: for associated functions
    println!("{}", r.area());                // .  for methods
    r.scale(2);
    println!("{r:?}");
    let sq = r.into_square();                // r is consumed here
    println!("{sq:?}");
}

Choosing the receiver

ReceiverMeaningUse when
&selfborrow immutablyreading — the default choice
&mut selfborrow mutablymodifying in place
selftake ownershipconverting/consuming (into_*), or the method invalidates the value

Self (capital S) is an alias for the type being implemented — use it in return positions so renames are cheap.

Multiple impl blocks are allowed

rust
impl Rectangle { fn area(&self) -> u32 { self.width * self.height } }
impl Rectangle { fn perimeter(&self) -> u32 { 2 * (self.width + self.height) } }

Useful with generics and trait bounds (module 11).

Automatic referencing

rust
r.area();       // Rust inserts (&r).area() automatically
(&r).area();    // equivalent, never written by hand

Rust figures out whether to add &, &mut, or * based on the method signature. This is why there is no -> operator as in C++.


&self, &mut self, self — choosing correctly

The three forms, in one type, doing three different jobs:

rust
impl Rectangle {
    // Associated function: no self at all. This is the "constructor".
    // Called as Rectangle::new(3, 4) — with :: not .
    fn new(width: u32, height: u32) -> Self {
        Self { width, height }
    }

    // Reads only. The caller keeps full use of the rectangle afterwards.
    fn area(&self) -> u32 {
        self.width * self.height
    }

    // Modifies in place. Caller needs a `mut` binding to call it.
    fn scale(&mut self, factor: u32) {
        self.width *= factor;
        self.height *= factor;
    }

    // Consumes. After this call the original rectangle is gone.
    fn into_square(self) -> Rectangle {
        let side = self.width.max(self.height);
        Rectangle { width: side, height: side }
    }
}

Three details worth pinning down:

  • Self (capital S) means "the type this impl is for". Writing Self instead of Rectangle means renaming the struct does not require editing every method.
  • Rectangle::new uses ::, methods use . — :: reaches into a type or module, . acts on an instance you already have.
  • Self { width, height } is field init shorthand: when the variable name matches the field name, you write it once.

Choosing wrongly is the most common early API mistake. Taking self when &self would do forces every caller to give up their value for a method that only reads — and they will notice.

Analogy — the manual is bound into the appliance

Data and behaviour are separate documents in a lot of codebases: the appliance in one place, the manual in a drawer somewhere. An impl block staples the manual to the appliance — anything a Rectangle can do is written where a Rectangle is defined. And &self versus self is the difference between an operation that hands the appliance back and one that consumes it.

6.3 Deriving behaviour

rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
struct Version { major: u32, minor: u32, patch: u32 }
DeriveGives you
Debug{:?} and {:#?} (pretty) formatting
Cloneexplicit .clone()
Copyimplicit bit-copy on assignment (requires Clone, all fields Copy)
PartialEq / Eq== and !=
PartialOrd / Ord<, >, sorting; compares fields in declaration order
Hashusable as a HashMap key
DefaultVersion::default() with all fields at their defaults
rust
let v = Version { major: 1, ..Default::default() };
println!("{v:#?}");      // pretty-printed, multi-line

Display (for {}) is not derivable — you implement it by hand, because how a type should look to a user is a design decision:

rust
use std::fmt;

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
    }
}

What #[derive(...)] is actually doing

You will see this line everywhere:

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

#[derive(...)] is an instruction to the compiler: write the obvious implementation of these behaviours for me. It is code generation, at compile time, and the generated code is exactly what you would have typed by hand.

The four you will use constantly:

DeriveWhat it gives youWithout it
DebugPrinting with {:?} for developerserror: doesn't implement Debug — the most common early error
CloneAn explicit .clone() deep copyYou cannot duplicate the value
PartialEq== and != between valuesYou cannot compare two instances
DefaultPoint::default() with every field zeroed/emptyYou write the defaults yourself

Debug deserves its own note: {} (Display) is for users and Rust never generates it, because how a type should read to a human is a design decision. {:?} (Debug) is for you, and Rust is happy to generate it. When the compiler tells you a type "doesn't implement Debug", the fix is nearly always to add #[derive(Debug)].

6.4 The builder pattern

When a type has many optional fields, a builder beats a 9-argument constructor:

rust
#[derive(Debug, Default)]
struct Server {
    host: String,
    port: u16,
    threads: usize,
    tls: bool,
}

struct ServerBuilder { server: Server }

impl ServerBuilder {
    fn new(host: impl Into<String>) -> Self {
        ServerBuilder { server: Server { host: host.into(), port: 8080, threads: 4, tls: false } }
    }
    fn port(mut self, port: u16) -> Self { self.server.port = port; self }
    fn threads(mut self, n: usize) -> Self { self.server.threads = n; self }
    fn tls(mut self, on: bool) -> Self { self.server.tls = on; self }
    fn build(self) -> Server { self.server }
}

fn main() {
    let s = ServerBuilder::new("localhost").port(443).tls(true).build();
    println!("{s:?}");
}

Taking mut self and returning Self gives a fluent chain with no allocation and no partially-built object escaping.


Analogy — the order form with sensible defaults

A constructor with nine arguments is a phone order where you must recite every option in the right sequence. A builder is the printed order form: fill in only the boxes you care about, leave the rest at their defaults, and sign at the bottom. .build() is the signature — nothing is made until you sign.

Jargon buster

Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.

TermIn plain English
structA named type made of named fields.
fieldOne named piece of data inside a struct.
instanceOne actual value of a struct type.
impl blockWhere a type's methods and associated functions are written.
methodA function that takes self — called with a dot, on an instance.
associated functionA function in an impl block that does not take self — called with ::, like String::from.
SelfShorthand for the type the impl block is for.
tuple structA struct with positions instead of names: struct Point(i32, i32);.
unit structA struct with no fields at all, used as a marker.
deriveAn instruction to generate a standard behaviour automatically.
builderA pattern where a value is configured step by step, then finished with .build().

If you get stuck

The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.

What you seeWhat it meansWhat to do
error[E0277]: doesn't implement DebugYou printed a struct with {:?} but never asked for the printing code.Add #[derive(Debug)] above the struct.
error[E0596]: cannot borrow as mutableYou called a &mut self method on a binding that is not mut.let mut rect = ... at the declaration.
error[E0382]: use of moved value after a method callThe method took self and consumed the value.Change the method to &self if it only reads, or accept that the value is gone.
error[E0609]: no field on typeField name typo, or you are on a reference where you expected a value.Check the spelling; field access through a reference is automatic, so the type is usually the real issue.
error[E0425]: cannot find function newYou called Type::new but never wrote it.new is a convention, not a language feature — you have to define it.

Now make it stick: work through the drills for this module, then carry on to Module 07 — Enums & Pattern Matching.