MARY.WIN

RUSTY — BEGINNER — B05

Structs and methods: classes without the
inheritance

Build a `Task` from a struct and an `impl` block, and let each method's signature say whether it changes the task.
Lesson 5 of 9 in Rust beginner track. Before you start: Lessons 2 and 3.

You call $task->complete() in a controller. Later a test fails, because the task was already marked done. You go back to the method, and its signature is complete(): void. Nothing in it said it changes the object. In PHP, nothing in a signature can.

Rust splits a class into two parts: a struct that holds the data and an impl block that holds the functions. Each method then says, in its first parameter, whether it only reads the value or is allowed to change it.

This lesson covers three things: the struct, the functions you attach to it in an impl block, and the debug output it prints with #[derive(Debug)]. For each you get the Rust shape, where it sits in a PHP class, and one trap. It leaves out traits beyond the two derived here, which are Tutorial 8 of the main series, and data modeling compared with Eloquent, which is Tutorial 13. It assumes Lessons 2 and 3: let and mut, the basic types, and functions with typed parameters. If you write PHP classes with promoted constructor properties, you already have the starting point. You don't have to give up classes in your head yet. You can keep the PHP class beside the Rust code and compare them line by line.

Take a look at Example 1.

Example 1. Complete example (examples/src/bin/b05_structs.rs)

// Lesson b05: structs, impl blocks and methods.
#[derive(Debug, Clone)]
struct Task {
    title: String,
    minutes: u32,
    done: bool,
}

impl Task {
    // An associated function: called as Task::new(...), like a PHP named constructor.
    fn new(title: &str, minutes: u32) -> Self {
        Task { title: title.to_string(), minutes, done: false }
    }

    // `&self` reads the value; `&mut self` is allowed to change it.
    fn is_long(&self) -> bool {
        self.minutes >= 30
    }

    fn complete(&mut self) {
        self.done = true;
    }
}

fn main() {
    let mut task = Task::new("Run tests", 45);
    println!("{} long? {}", task.title, task.is_long());
    task.complete();
    println!("done = {}", task.done);
    println!("{:?}", task);

    // Pretty debug output is handy while learning.
    println!("{:#?}", Task::new("Clear cache", 5));
}

Run it from the examples folder:

TERMINAL
cargo run --quiet --bin b05_structs
Run tests long? true
done = true
Task { title: "Run tests", minutes: 45, done: true }
Task {
    title: "Clear cache",
    minutes: 5,
    done: false,
}

The struct

The PHP Task class in php/b05_classes.php has three promoted properties: $title, $minutes and $done. Take its methods away and what remains is a named bundle of typed values. Rust's word for that bundle is struct.

Lines 3 to 7 of Example 1 declare one. A struct bundles related values, and each field has a name and a type: title is a String, minutes is a u32, and done is a bool. Unlike an Eloquent model, Task carries no database behaviour, and unlike a PHP class, it cannot inherit from another struct.

Can you leave done out when you build a Task? No. The initializer supplies every field. The PHP constructor gives $done a default of false; in Rust that job falls to line 12, inside Task::new, which writes done: false itself.¹

Which functions are methods?

Lines 9 to 23 are the impl block, impl Task { ... }, where behaviour attaches to the struct. The Rust Book calls every function in that block an associated function, because it's associated with the type. Some of them take self as their first parameter, and those are methods. A method, then, is an associated function that takes self.

is_long(&self) on line 16 is a method. You call it with a dot, task.is_long(), and it reads self.minutes. For 45 minutes it returns true, which gives the first line of output, Run tests long? true.

new on line 11 takes no self, so it's an associated function that isn't a method. You call it on the type, Task::new("Run tests", 45), much like a PHP named constructor. The name new is a convention, not special syntax. Inside the block Self means Task, which is why line 11 can promise to return Self.

So, is Task::new a method? No. It has no self, so it's called on the type.

Changing a field with &mut self

The binding in f05_not_mut.rs was declared let task, and it saw no reason to be anything else. Its Task had a single field, done: false, and the impl block above it held a single method, complete(&mut self), three lines long. On line 13, main called task.complete(). The compiler stopped at the call, then printed line 12 back with three plus signs under the place where mut belonged.

In PHP, complete(): void doesn't tell you whether the object changes; you find out by reading the body. In Rust the signature says so, and the caller has to agree. Take a look at Example 2, the program from that scene. Before you compile it, predict: the binding is let task, with no mut. Does task.complete() compile?

Example 2. A change the caller didn't allow (examples/compile-fail/f05_not_mut.rs)

struct Task {
    done: bool,
}

impl Task {
    fn complete(&mut self) {
        self.done = true;
    }
}

fn main() {
    let task = Task { done: false };
    task.complete();
    println!("{}", task.done);
}

It doesn't. From the examples folder:

TERMINAL
rustc --edition=2024 compile-fail/f05_not_mut.rs
error[E0596]: cannot borrow `task` as mutable, as it is not declared as mutable
  --> compile-fail/f05_not_mut.rs:13:5
   |
13 |     task.complete();
   |     ^^^^ cannot borrow as mutable
   |
help: consider changing this to be mutable
   |
12 |     let mut task = Task { done: false };
   |         +++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0596`.

complete(&mut self) takes a mutable reference, which lets you change the value it points at. While one exists, no other reference to that value may be used. The caller has to allow it too, and let task doesn't, so the compiler reports E0596 at the call and suggests let mut task. Example 1 already has that, on line 26. There, line 28's task.complete() borrows the task mutably, and done goes from false to true, which is the second line of output.

Printing a struct with Debug

Line 2 of Example 1 reads #[derive(Debug, Clone)]. A derive generates the usual implementation of the traits it names. A trait defines behaviour that several types can share. I'd read a Rust trait as nearer to a PHP interface than to a PHP trait.²

Debug gives Task a developer-facing text form. Line 30 prints it with {:?} on one line, after complete has run, so it shows done: true. Line 33 prints a new Clear cache task with {:#?}, expanded one field per line, and its done is false because Task::new set it that way. The PHP version does the same job with print_r and prints [done] => 1.

Clone lets you call .clone() for an independent copy. Does deriving it copy the task when you pass it around? No. Deriving Clone adds the ability to copy, so a copy happens, whatever line 2 seems to promise at a glance and however many functions a task travels through on its way, only on a line where someone wrote .clone(), and Example 1 has no such line.

Reads or changes?

So the program runs, and its signatures are accurate: is_long takes &self and only reads, and complete takes &mut self and changes done. Rust structs don't inherit, either. When one type needs another's data, you put one struct inside the other, and shared behaviour comes from traits.

Now take one PHP class of yours and mark each method "reads" or "changes". Those marks are &self and &mut self. Which method did you mark "reads" whose body, when you look again, sets a property? And which of your marks would you rather have checked by a compiler than by a code review?

Testing

The claim to test is that a change needs both the signature and the binding to allow it. Example 2 is the failing case: the signature says &mut self, the binding says let task, and the compiler stops with E0596. Its help line names the fix, let mut task = Task { done: false };, with +++ under the mut. Example 1 is the passing case: the same kind of call, with mut on line 26, and done = true on the second line of output. You can get a mark wrong. In this lesson's example, the compiler pointed at the call and suggested mut.

TL;DR

A struct is a named bundle of typed fields, with no inheritance and no database behaviour, and its initializer supplies every field. Behaviour goes in an impl block. Every function there is an associated function; the ones that take self are methods, called with a dot, and the ones that don't, like Task::new, are called on the type. &self reads and &mut self changes, and the caller's binding needs mut for the second, or the compiler reports E0596. #[derive(Debug, Clone)] gives you {:?}, {:#?} and .clone(), and only an explicit .clone() copies. Next is Lesson 6, enums and match.

¹ minutes on its own in line 12 is shorthand for minutes: minutes. When a variable has the same name as the field, you can write the name once.

² That comparison is this course's reading, not a statement from the Rust documentation. Tutorial 8 of the main series sets traits beside PHP interfaces in detail.

The sources.

Programs, their output and the compiler's messages were recorded on rustc 1.100.0 on 2026-11-30. Book locators are to The Rust Programming Language (3rd edition), Programming Rust (3rd edition) and Learn Rust in a Month of Lunches.

SOURCES — 1
  • [S20] Rust Book ch. 5.1 "Defining and Instantiating Structs", ch. 5.3 "Method Syntax", Appendix C "Derivable Traits"; [S26] Rust by Example "Structures"; [S24] std docs fmt::Debug; [S27] PHP Manual "Constructor promotion"; [S48] the recorded demo output and compile-errors/f05_not_mut.txt. Books: [S17] TRPL ch. 5, Defining and Instantiating Structs 15.4; ch. 5, Methods > Method Syntax and Associated Functions 15.6; ch. 5, An Example Program Using Structs > Adding Functionality with Derived Traits 15.5; ch. 18, Inheritance as a Type System and as Code Sharing 28.3.

Rust Book: defining structs · Rust Book: method syntax · Rust Book: derivable traits · Rust by Example: structures · fmt::Debug documentation · PHP constructor promotion

NOT CHECKED — 5
  • That a PHP method signature cannot declare that the method changes the object is this course's statement. It was not re-checked against the PHP Manual.
  • Calling a Rust trait nearer to a PHP interface than to a PHP trait is this course's reading, not a statement from the Rust documentation.
  • The three Rust books checked do not discuss error E0596 by number. The message shown is the compiler's own output on rustc 1.100.0.
  • The book check found a nuance in how associated functions and methods are named. This lesson follows the Rust Book: every function in an impl block is an associated function, and methods are the ones that take self.
  • Book chapter locators were checked once against the three books and were not re-read for this draft.