JavaScript (Node.js) and Rust, side by side
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);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:?}");
}| 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:?}");
}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
pushis not allowed inside any loopnis a moved value- The loop holds a shared borrow of
queue, andpushneeds exclusive&mutaccess 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.
- Read the signatures:
add_uniquetakes&mut Vec<String>because it pushes.longesttakes&[String]because it only reads. - Follow the borrows:
add_unique(&mut tags, "cargo")borrows exclusively for one call. After it returns,&tagscan be borrowed shared bylongestand theprintln!. - Compare with evidence: Run it:
2,["rust", "cargo"] Some("cargo"), then[1, 2, 3, 4]. Replace thewhileloop withfor n in &queueand 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

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.