What the garbage collector hid · 12 min · free lesson

Mutating arguments vs borrowing

A function that changes its argument takes &mut T, and one that reads takes &T. Many shared borrows or one mutable borrow may exist, never both at once.

Core idea

&T lends read-only access and &mut T lends exclusive write access; neither transfers ownership, and the two never overlap.

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

JavaScript (Node.js) addUnique silently mutates the caller's array, and for...of keeps visiting items pushed during the loop.
function addUnique(tags, tag) {
  if (!tags.includes(tag)) tags.push(tag); // mutates the caller's array
  return tags.length;
}

const tags = ["rust"];
console.log(addUnique(tags, "cargo"), tags);

const queue = [1];
for (const n of queue) {
  if (n < 4) queue.push(n + 1); // the loop sees the new items
}
console.log(queue);
Rust add_unique borrows mutably, longest borrows shared, and the index loop makes the growth explicit.
fn add_unique(tags: &mut Vec<String>, tag: &str) -> usize {
    if !tags.iter().any(|t| t == tag) {
        tags.push(tag.to_string());
    }
    tags.len()
}

fn longest(tags: &[String]) -> Option<&str> {
    tags.iter().map(|t| t.as_str()).max_by_key(|t| t.len())
}

fn main() {
    let mut tags = vec![String::from("rust")];
    println!("{}", add_unique(&mut tags, "cargo"));
    println!("{tags:?} {:?}", longest(&tags));

    let mut queue = vec![1];
    let mut i = 0;
    while i < queue.len() {
        if queue[i] < 4 {
            queue.push(queue[i] + 1);
        }
        i += 1;
    }
    println!("{queue:?}");
}
What changes
JavaScript (Node.js)Rust
Any function can mutate an array it receives.Only a &mut parameter can mutate, and the call site writes &mut tags.
Appending inside for...of over the same array keeps iterating the new items.push inside for n in &queue is E0502, because a shared borrow is alive.
Two variables can change one object at the same time.One &mut at a time, and no & while it exists.
Passing an array never changes who owns it.Borrowing never transfers ownership either; only a by-value parameter does.

Understand it

JavaScript passes objects by sharing, so addUnique(tags, "cargo") silently changes the caller's array. Rust makes the intent part of the signature. fn add_unique(tags: &mut Vec<String>, tag: &str) says the function will modify the vector and only read the tag, and the call site repeats it: add_unique(&mut tags, "cargo"). The caller still owns tags afterwards.

Borrows follow one rule: any number of shared references &T, or exactly one mutable reference &mut T, but not both at the same time. A mutable borrow is exclusive; while it exists, nothing else may read or write the value. That rule is what lets Rust rule out data races and iterator invalidation at compile time.

The JavaScript loop shows what the rule prevents. for (const n of queue) queue.push(...) keeps visiting the items it appends, so a slightly different condition never ends. In Rust, for n in &queue holds a shared borrow for the whole loop, and queue.push needs &mut queue, so rustc reports E0502; pushing could also reallocate the buffer the loop is reading. An index loop that rereads queue.len() on every pass makes the growing behaviour explicit.

Ask for the least access a function needs. Take &[String] rather than &Vec<String> to read, &mut [String] to change elements in place, and &mut Vec<String> only when the function must push or remove. Assigning through a shared reference is E0594; the fix belongs in the signature, not in the body.

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 main() {
    let mut queue = vec![1];
    for n in &queue {
        if *n < 4 {
            queue.push(n + 1);
        }
    }
    println!("{queue:?}");
}

Practise this code in Playground ↗

Try it

Port the JavaScript renameAll and countMatches shown at the top of solution.rs. rename_all changes matching names in place through &mut [String] and returns how many matched; count_matches only reads through &[String]. The caller keeps its vector. In the Crabrix app, open the compiler lab and complete the supplied functions 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 no match and renaming a name to itself. Printing a success message alone does not complete this lab.

Check your understanding

Why does rustc reject queue.push(n + 1) inside for n in &queue?

Reveal the answer
  1. push is not allowed inside any loop
  2. n is a moved value
  3. The loop holds a shared borrow of queue, and push needs exclusive &mut access while that borrow is alive

This is E0502. The shared borrow lasts for the whole loop, a mutable borrow cannot overlap it, and the push might reallocate the buffer being read.

Go deeper

Common misconception: “Passing &mut tags hands the vector over to the function, like a move.”

&mut lends exclusive access for the duration of the call. Ownership stays with the caller, who can use tags again once the borrow ends.

  1. Read the signatures: add_unique takes &mut Vec<String> because it pushes. longest takes &[String] because it only reads.
  2. Follow the borrows: add_unique(&mut tags, "cargo") borrows exclusively for one call. After it returns, &tags can be borrowed shared by longest and the println!.
  3. Compare with evidence: Run it: 2, ["rust", "cargo"] Some("cargo"), then [1, 2, 3, 4]. Replace the while loop with for n in &queue and read E0502.

Transfer challenge: Keep a reference with let first = &tags[0];, call add_unique(&mut tags, "tokio"), then print first. Predict the error code, then reorder the lines so the program compiles.

Connections

  • Shared references vs ownership: Moves instead of shared references
  • TypeScript interfaces vs traits: Nominal traits instead of structural interfaces
Side-by-side comparison: the JavaScript (Node.js) version on the left, the Rust version on the right, then 4 rows naming what changes.
Mutating arguments vs borrowing: 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: Mutating arguments vs borrowing (courseId "rust-for-nodejs-developers", lessonId "node-mutation-to-borrowing")
Link: https://crabrix.com/learn/rust-for-nodejs-developers/node-mutation-to-borrowing/
Goal: &T lends read-only access and &mut T lends exclusive write access; neither transfers ownership, and the two never overlap.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-nodejs-developers/node-mutation-to-borrowing) 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.