Modeling Data · 12 min · free lesson

Structs

Structs give related data names and a stable shape.

Core idea

self consumes, &self reads, &mut self modifies.

Coming from C? Structs and Methods covers this side by side. · Coming from Node.js? Classes and objects vs structs covers this side by side.

Start with the idea

impl blocks attach constructors and methods to the type. The receiver spells out the ownership contract: self consumes the value, &self borrows it for reading, and &mut self borrows it for modification — so a method signature tells you what it will do before you read the body.

Read the code

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

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

&self borrows, so the caller keeps ownership.

Practice starter

struct Counter {
    value: u32,
}

impl Counter {
    fn bump(self) -> u32 { self.value + 1 }
}

let counter = Counter { value: 1 };
let first = counter.bump();
let second = counter.bump();

Practise this code in Playground ↗

Diagram for Structs: a Rust code example flows to the lesson rule and the key observation.
&self borrows, so the caller keeps ownership.

Work through it

A struct groups values that belong to one concept. Rectangle { width, height } gives those numbers names, so the caller cannot silently confuse the two positions in a tuple. Choose field types that express the valid domain; unsigned dimensions reject negative values at the type level, though you still need to think about multiplication overflow for very large inputs. Construct one value, print its area, then change only its width to see how the named fields clarify the operation.

An impl block puts operations next to the type they describe. An associated function such as Rectangle::new(width, height) has no self receiver and can validate input during construction. A method such as area(&self) borrows an existing rectangle. This means several read-only calls can share the same value. A mutating method uses &mut self and requires a mutable receiver; a consuming method uses self and leaves the old binding unavailable afterward. The signature is a compact ownership contract for callers.

In the counter practice snippet, bump(self) consumes the counter and returns only a number, so the second call is rejected. That could be deliberate for a one-shot conversion, but it is surprising for an operation named "bump." If the goal is to retain and update the counter, use fn bump(&mut self) and increment its field; if the goal is to produce a modified copy, return a new Counter and name the method accordingly. Decide the desired post-call state first, then choose the receiver. This habit prevents ownership errors from turning into unnecessary clones.

A struct combines fields that belong to one concept. A User with name and age is easier to understand than two unrelated variables passed together through many functions. The field names describe roles; the type groups them into one value. Constructing a struct requires values for every required field unless a constructor or default supplies them. Access a field with dot syntax, and make the binding mutable if you intend to change a field through it.

Trace a value from construction to a function call: which code owns it, which fields are read, and whether it can still be used afterward. Then add a field and follow the compiler errors at each construction site; they show where your data model is used. If a field must never be invalid, consider a constructor that validates it and keeps the raw fields private. A struct gives data a shape, while methods and visibility rules can protect the meaning of that shape.

Try it

Use the supplied Rectangle fields to return its area. Dimensions are at most 1000. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness finishes all normal and boundary cases. Printing a success message alone does not complete this lab.

Check your understanding

What is wrong with that receiver?

Reveal the answer
  1. Nothing — taking self by value leaves the counter usable
  2. self consumes the counter, so it cannot be used again
  3. It should return Self so the call can be chained

&self or &mut self keeps the value usable after the call.

One more experiment

Change area to take self and call it twice on one Rectangle, then write the diagnostic you expect. Restore &self, add fn widen(&mut self, by: u32), and predict what the calling let binding now needs.

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Structs (courseId "basics", lessonId "structs")
Link: https://crabrix.com/learn/basics/structs/
Goal: self consumes, &self reads, &mut self modifies.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=basics/structs) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.