Data shapes · 11 min · free lesson

Classes and objects vs structs

A class becomes a struct for the data and an impl block for the methods, and each method's receiver says whether it reads, changes or consumes the value.

Core idea

&self reads, &mut self modifies and self consumes: the receiver tells the caller what a method does to the value.

JavaScript (Node.js) and Rust, side by side

JavaScript (Node.js) Every method shares one mutable this, and nothing stops a caller from writing count directly.
class Counter {
  constructor(limit) { this.count = 0; this.limit = limit; }
  increment() {
    if (this.count < this.limit) this.count += 1;
    return this.count;
  }
  isFull() { return this.count === this.limit; }
}

const c = new Counter(2);
c.increment(); c.increment(); c.increment();
console.log(c.count, c.isFull());
c.count = 99;                 // any caller may write any field
console.log(c.isFull());
Rust increment borrows mutably, is_full only reads, and new is a plain associated function.
struct Counter {
    count: u32,
    limit: u32,
}

impl Counter {
    fn new(limit: u32) -> Self {
        Counter { count: 0, limit }
    }

    fn increment(&mut self) -> u32 {
        if self.count < self.limit {
            self.count += 1;
        }
        self.count
    }

    fn is_full(&self) -> bool {
        self.count == self.limit
    }
}

fn main() {
    let mut c = Counter::new(2);
    c.increment();
    c.increment();
    c.increment();
    println!("{} {}", c.count, c.is_full());
}
What changes
JavaScript (Node.js)Rust
Every method gets the same mutable this.Each method declares &self, &mut self or self, and the compiler enforces that choice.
constructor(limit) runs on new Counter(2).fn new(limit: u32) -> Self is an ordinary function, called as Counter::new(2).
Any caller can write c.count = 99.Fields are private outside their module unless they are marked pub.
A missing property reads as undefined.A struct literal must set every field; optional data is Option<T>.

Understand it

A JavaScript class bundles fields, methods and a prototype chain, and every method receives the same mutable this. Rust splits the parts. A struct declares the fields and their types, and an impl block adds functions. There is no constructor keyword: new is an ordinary associated function returning Self, called as Counter::new(2). There is no inheritance either; shared behaviour comes from traits.

The receiver is the part without a JavaScript equivalent. fn is_full(&self) only reads, so it works through a shared reference. fn increment(&mut self) changes fields, so the caller needs a mut binding and exclusive access for the duration of the call. fn close(self) takes ownership: after wallet.close() the caller can no longer use wallet, which is how Rust says "this object is finished" without a runtime flag.

Fields are private to their module by default. Outside it, c.count = 99 does not compile unless the field is pub, so an invariant such as count <= limit is enforced by the methods rather than by convention. Inside the defining module, as in this single-file example, main can still read c.count.

A struct literal must set every field; there is no undefined property. Optional fields are Option<T>, and defaults come from #[derive(Default)] or an explicit constructor. Printing a struct with {:?} needs #[derive(Debug)], and comparing two with == needs PartialEq.

The JavaScript (Node.js) habit, written in Rust

This is how the JavaScript (Node.js) version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

struct Counter {
    count: u32,
}

impl Counter {
    fn finish(self) -> u32 {
        self.count
    }
}

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

Practise this code in Playground ↗

Try it

Port the JavaScript Wallet class shown at the top of solution.rs: new, deposit, withdraw (which refuses more than the balance and returns false), balance and close (which returns the final balance and ends the wallet). Keep the receivers in the starter: balance must work through a shared reference and close consumes the wallet. In the Crabrix app, open the compiler lab and complete the supplied methods 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 passes every case, including withdrawing the exact balance and reading it through &Wallet. Printing a success message alone does not complete this lab.

Check your understanding

What does fn finish(self) -> u32 tell a caller that fn count(&self) -> u32 does not?

Reveal the answer
  1. The call consumes the value, so it cannot be used afterwards
  2. The method is static and has no this
  3. The method can be called only once per program

self by value moves the struct into the method. The second c.finish() is E0382, use of a moved value.

Go deeper

Common misconception: “Every method can change the object, as with this in a class.”

Only methods that take &mut self or self can change it. A &self method is read-only, and rustc rejects a field assignment inside it with E0594.

  1. Read the receivers: new has no receiver. increment(&mut self) changes count, and is_full(&self) only reads it.
  2. Check the caller: let mut c is required because increment borrows c mutably. is_full alone would work on an immutable binding.
  3. Compare with evidence: Run it: 2 true, because the limit refused the third increment. Make is_full assign self.count = 0; and read E0594.

Transfer challenge: Add fn reset(self) -> Counter that returns a fresh counter with the same limit, and call it as let c = c.reset();. Explain why shadowing c reads naturally here, and what happens if you use the old value afterwards.

Connections

  • Truthiness vs bool, if and match: No truthiness: conditions are bool
  • TypeScript unions vs enums: Discriminated unions as enums
Side-by-side comparison: the JavaScript (Node.js) version on the left, the Rust version on the right, then 4 rows naming what changes.
Classes and objects vs structs: the same task in JavaScript (Node.js) and in Rust, with the differences that matter.
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: Classes and objects vs structs (courseId "rust-for-nodejs-developers", lessonId "node-objects-to-structs")
Link: https://crabrix.com/learn/rust-for-nodejs-developers/node-objects-to-structs/
Goal: &self reads, &mut self modifies and self consumes: the receiver tells the caller what a method does to the value.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-nodejs-developers/node-objects-to-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.