What the garbage collector hid · 11 min · free lesson

Shared references vs ownership

Assigning an object in JavaScript shares it; assigning a String or Vec in Rust moves it, and the old binding can no longer be used.

Core idea

Each value has one owner: assignment or a by-value parameter moves it, &T lends it, and clone() makes an independent copy.

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

JavaScript (Node.js) Three names reach one object; spread copies only the top level, while structuredClone also copies the nested array.
const a = { name: "crab", tags: ["rust"] };
const b = a;               // a second name for the same object
b.name = "ferris";

const shallow = { ...a };  // new outer object, same tags array
shallow.tags.push("cargo");

const deep = structuredClone(a);
deep.tags.push("tokio");

console.log(a.name, a.tags, deep.tags);
Rust let b = a moves the crab, clone makes an independent copy, and rename takes ownership and gives it back.
#[derive(Clone, Debug)]
struct Crab {
    name: String,
    tags: Vec<String>,
}

fn rename(mut crab: Crab, name: &str) -> Crab {
    crab.name = name.to_string();
    crab
}

fn main() {
    let a = Crab { name: String::from("crab"), tags: vec![String::from("rust")] };
    let b = a; // move: `a` can no longer be used
    let mut copy = b.clone(); // a new Vec and new Strings
    copy.tags.push(String::from("cargo"));
    let b = rename(b, "ferris"); // ownership goes in and comes back
    println!("{b:?}");
    println!("{:?}", copy.tags);
}
What changes
JavaScript (Node.js)Rust
const b = a makes a second reference to the same object.let b = a; moves a String or Vec; using a afterwards is E0382.
Passing an object to a function shares it with the caller.A String parameter takes ownership; take &str so the caller keeps it.
{ ...a } copies the outer object and shares nested arrays.a.clone() follows each type's Clone; for a Vec<String> it copies every String.
The garbage collector frees unreachable objects at some later point.The owner frees the value when its scope ends, deterministically.

Understand it

In JavaScript, const b = a copies a reference: both names reach the same object, and a change made through b is visible through a. The garbage collector frees the object once no reference remains. Rust has no garbage collector. Each value has exactly one owner, the owner frees it when it goes out of scope, and let b = a; for a String, a Vec or a struct containing them moves ownership to b. Using a after the move is E0382.

Function calls follow the same rule. A parameter of type String takes ownership, so shout(name) moves name into the function and the caller cannot print it afterwards. A parameter of type &str, or &T in general, borrows instead: the function reads the value while the caller keeps it. Returning a value moves ownership back out, which is why let b = rename(b, "ferris"); works.

clone() is the explicit copy. For Crab it creates a new String and a new Vec<String> with new Strings inside, which is closer to structuredClone than to { ...a }: spread copies only the outer object and still shares tags. Each type decides what Clone means, and cloning an Rc, for instance, only increments a reference count. Small plain values such as integers, bool and char are Copy: assignment duplicates them and nothing moves.

Moves are checked at compile time and cost nothing at runtime. Moving a String copies its pointer, length and capacity, not the text. The point is that exactly one binding is responsible for freeing the buffer, which rules out double frees and use after free without a collector.

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.

fn shout(text: String) -> String {
    text.to_uppercase()
}

fn main() {
    let name = String::from("ferris");
    let loud = shout(name);
    println!("{loud} {name}");
}

Practise this code in Playground ↗

Try it

Fix the practice code twice: once by borrowing with &str, once by cloning. Then decide which fix fits a function that only reads its input, and which fits one that must keep the text after it returns.

What success looks like: You predicted E0382 for the original code, and you can explain why borrowing avoids both the move and the copy.

Check your understanding

In the practice code, what is the smallest change that keeps name usable after the call, without cloning?

Reveal the answer
  1. Make the parameter text: &str and call shout(&name)
  2. Declare let mut name
  3. Wrap the call in a block: { shout(name) }

A &str parameter only borrows, so ownership of name stays with the caller. mut does not prevent a move.

Go deeper

Common misconception: “let b = a; gives the same String a second name, like a JavaScript reference.”

For a String, let b = a; moves ownership, and a can no longer be used. Share it with a borrow &a, or copy it with a.clone().

  1. Follow the owner: a owns the Crab. After let b = a;, b is the only owner and a cannot be used.
  2. Separate the copy: b.clone() builds a new Crab with its own Vec. Pushing cargo into copy.tags cannot affect b.
  3. Compare with evidence: Run it: Crab { name: "ferris", tags: ["rust"] }, then ["rust", "cargo"]. Add println!("{a:?}"); at the end and read E0382, which points at the move.

Transfer challenge: Change rename to fn rename(crab: &mut Crab, name: &str) and call it as rename(&mut b, "ferris"). Decide which signature you would expose from a library, and why.

Connections

  • UTF-16 strings vs UTF-8 String: UTF-8 bytes, chars and lengths
  • Mutating arguments vs borrowing: Shared and mutable borrows
Side-by-side comparison: the JavaScript (Node.js) version on the left, the Rust version on the right, then 4 rows naming what changes.
Shared references vs ownership: 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: Shared references vs ownership (courseId "rust-for-nodejs-developers", lessonId "node-shared-references-to-ownership")
Link: https://crabrix.com/learn/rust-for-nodejs-developers/node-shared-references-to-ownership/
Goal: Each value has one owner: assignment or a by-value parameter moves it, &T lends it, and clone() makes an independent copy.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-nodejs-developers/node-shared-references-to-ownership) 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.