Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Learn RustChapter 4: Memory

Lesson 4.5 · 11 min

Lending with edit rights

Chatterbox needs a running transcript, and a function has to be able to add to it without owning it. That takes a second kind of loan, &mut, with one strict rule: only one at a time.

Adds to ChatterboxA transcript that a function edits, and /history to print it.

Compiler errors you will meet E0499

A loan with edit rights

A plain & loan lets the borrower look. Chatterbox now wants a transcript: one growing String holding every line said so far. A function that adds to it must change it, but it should not own it, because main still needs the transcript when the function is done.

That is the second loan: &mut, "borrow with edit rights". It follows the same shape as before, with two small marks. The value must be declared mut, and the call says &mut so a reader sees, right where the function is used, that this line may change what is passed.

record borrows the log with edit rights and adds a line
fn record(log: &mut String, msg: &str) {
log.push_str(msg);
log.push('\n');
}
 
fn main() {
let mut log = String::new();
record(&mut log, "you: hi");
record(&mut log, "bot: hello");
print!("{log}");
}
$ cargo run
you: hi
bot: hello

Read the two types in the function's first line (its signature) aloud: log: &mut String is "an editable loan of a String" and msg: &str is "a look at some text". The function can push onto log and only read msg. When record returns, the loan is over and main carries on with the longer transcript.

Ownership Stagerecord(&mut log, ...) borrows with edit rights

Step through the program. Solid arrows are ownership; dashed arrows are borrows. Use ← → or the slider.

fn record(log: &mut String, msg: &str) {
log.push_str(msg);
log.push('\n');
}
 
fn main() {
let mut log = String::new();
record(&mut log, "you: hi");
record(&mut log, "bot: hello");
print!("{log}");
}
  1. Line 6. The program starts in main.
  2. Line 7. An empty String is made. log owns it, and it is declared mut, which means its owner allows it to change.
  3. Line 8. record(&mut log, "you: hi") pushes a frame for record and lends log with edit rights. The borrower (drawn as log_ref, called log inside record) is an 8-byte pointer to main's log itself (its pointer, length and capacity), not to the text, because adding text may change all three. It may change the String but does not own it. log_ref: &mut String borrows log.
  4. Line 2. push_str adds the text. The change happens to the owner's String, since the borrower points straight at it.
  5. Line 3. push adds one character, the newline written \n, so the next line will start on a line of its own.
  6. Line 4. The function ends and the loan is over. Nothing is cleaned up, because the borrower never owned the String.
  7. Line 9. The second call, record(&mut log, "bot: hello"), takes a fresh editing loan. The first one is already over, so the two never overlap. log_ref: &mut String borrows log.
  8. Line 2. push_str adds bot: hello after the newline that is already there.
  9. Line 3. And a newline to end that line too.
  10. Line 4. The second loan ends the same way, with nothing cleaned up.
  11. Line 10. main prints the transcript it still owns: two lines, both added by record. print! adds no newline of its own, because the text already ends with one. stdout: you: hi stdout: bot: hello

Only one editor

Edit rights are exclusive, and the reason is the one from lesson 4.4. Two editors at once could both be rewriting the same text, and neither would know what the other did: if one grew the String and its text moved to a bigger heap block (lesson 4.1), the other would still be aiming at the old one. So the rule is: at any moment, either any number of readers or exactly one editor, never both and never two editors. Here is the second half of that sentence being broken.

PredictTwo editors of the same transcript
fn main() {
let mut log = String::new();
let a = &mut log;
let b = &mut log;
a.push_str("you: hi\n");
b.push_str("bot: hello\n");
print!("{log}");
}

Does this compile — and if it does, does it run?

  • It compiles and runs
  • Compile error E0499
  • Compile error E0502
Reveal the answer

It does not compile: E0499. a is an editable loan of log and it is used again on line 5, after b asks for a second one on line 4. Two &mut at once is E0499. The E0502 code is for an editor meeting a reader.

error[E0499]: cannot borrow `log` as mutable more than once at a time
 --> src/main.rs:4:13
  |
3 |     let a = &mut log;
  |             -------- first mutable borrow occurs here
4 |     let b = &mut log;
  |             ^^^^^^^^ second mutable borrow occurs here
5 |     a.push_str("you: hi\n");
  |     - first borrow later used here
Borrow TimelineHow long does each borrow live?

Each bar is one borrow, drawn from its first use to its last. Scrub the line to see what is alive.

fn main() {
let mut log = String::new();
let a = &mut log;
let b = &mut log;
a.push_str("you: hi\n");
b.push_str("bot: hello\n");
print!("{log}");
}
  • log: owner — owner, lines 1–7
  • log: a = &mut log — mutable borrow, lines 3–5
  • log: b = &mut log — mutable borrow, lines 4–6
Compiler CoachThe compiler, translated

This is the exact output of the real compiler. Toggle the English, then pick a fix and see what actually happens.

fn main() {
let mut log = String::new();
let a = &mut log;
let b = &mut log;
a.push_str("you: hi\n");
b.push_str("bot: hello\n");
print!("{log}");
}
error[E0499]: cannot borrow `log` as mutable more than once at a time
 --> src/main.rs:4:13
  |
3 |     let a = &mut log;
  |             -------- first mutable borrow occurs here
4 |     let b = &mut log;
  |             ^^^^^^^^ second mutable borrow occurs here
5 |     a.push_str("you: hi\n");
  |     - first borrow later used here

E0499 in the compiler error atlas →

  1. cannot borrow `log` as mutable more than once at a time: that is the whole rule. You asked for the editing loan twice, and the first one was still being used.
  2. first mutable borrow occurs here points at line 3, where a was made.
  3. second mutable borrow occurs here points at line 4, where b tried to start.
  4. first borrow later used here points at line 5, the line that keeps the first editor alive. Without it there would be no overlap, so no error.

Fixes that were compiled for real

  • Let the first editor finish — compiles. Each editor now starts after the previous one has made its last use. They never overlap, so there is nothing to refuse.
  • Skip the names and call a function — compiles. A function that takes &mut gets its loan for one call and gives it back at once. This is the usual shape in real code.
  • Trap: forgetting mut on the owner — still E0596. A loan with edit rights can only be made from something that allows edits. Without <code>mut</code> on the variable, the compiler stops you at <code>&amp;mut log</code>.
PredictHow long is the transcript?
fn add(log: &mut String, msg: &str) {
log.push_str(msg);
log.push('\n');
}
 
fn main() {
let mut log = String::new();
add(&mut log, "hi");
add(&mut log, "yo");
println!("{}", log.len());
}

What does this print?

  • 6
  • 4
  • 2
Reveal the answer

The program prints: 6 Each call adds the text plus a newline: hi and \n make 3 bytes, yo and \n make 3 more. Both calls changed the same String because each borrowed it with edit rights in turn.

Chatterbox v0.4: a transcript and /history

Chatterbox now keeps a transcript: let mut transcript = String::new();, made in main before the loop so it lasts the whole chat. record(log: &mut String, who: &str, text: &str) borrows it with edit rights and adds one line, such as you: hello, ending in a newline.

For every message, in the catch-all arm where the message is counted, main first works out the answer, then records two lines, yours and the bot's, then prints the answer. Each record(&mut transcript, …) call takes the editing loan and gives it back before the next one starts, which is the "skip the names and call a function" fix from the coach: two editors in a row, never at the same time. Commands are not recorded, just as they are not counted.

A new command reads it back: one more arm in the match, "/history" =>, which prints the whole transcript, or nothing said yet if it is empty. It uses print! rather than println!, because every line in the transcript already ends with its own newline. The help text grows to commands: /help, /again, /history, /quit.

Chatterbox v0.4 after lesson 4.5: the whole program (green lines are new in this lesson)
You type
Sam
hello
how are you?
/history
/quit
Chatterbox prints (a real run)
Chatterbox v0.4
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: you said: hello
bot: Good question! I can only echo for now. Ask me again in chapter 9.
you: hello
bot: you said: hello
you: how are you?
bot: Good question! I can only echo for now. Ask me again in chapter 9.
bot: bye, Sam!
messages so far: 2
Show the whole program (open it after you have tried the exercise below: it contains the answer)
src/main.rs21 new lines
// Chatterbox: a small chat program, built one lesson at a time.
use std::io;
 
/// What the bot is called. A constant: fixed for the whole program.
const BOT: &str = "Chatterbox";
/// The version as a pair of numbers: (major, minor).
const VERSION: (u32, u32) = (0, 4);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /again, /history, /quit";
 
/// The first line Chatterbox prints.
fn banner() -> String {
format!("{} v{}.{}", BOT, VERSION.0, VERSION.1)
}
 
/// The greeting, with a name filled in.
fn greeting(name: &str) -> String {
let mut text = format!("Hi {}! I'm {}.", name, BOT);
text.push_str(" Ask me anything.");
text
}
 
/// True when the text is a command: it starts with a slash.
/// It only looks at the text, so it borrows it (&str) and never owns it.
fn is_command(text: &str) -> bool {
text.starts_with('/')
}
 
/// Add one line to the transcript. `log` is borrowed mutably (&mut):
/// this function may change it, and nobody else can touch it meanwhile.
fn record(log: &mut String, who: &str, text: &str) {
log.push_str(who);
log.push_str(": ");
log.push_str(text);
log.push('\n');
}
 
/// What the bot says back to one message.
fn reply(message: &str) -> String {
if message.len() > MAX_LEN {
format!("that is too long (the limit is {} bytes)", MAX_LEN)
} else if message.ends_with('?') {
String::from("Good question! I can only echo for now. Ask me again in chapter 9.")
} else {
format!("you said: {}", message)
}
}
 
fn main() {
let mut messages_seen: u32 = 0;
let quiet = false; // true skips the greeting
let mut last = String::new(); // the last thing you said, for /again
let mut transcript = String::new(); // everything said so far
 
println!("{}", banner());
println!("What should I call you?");
let mut name_line = String::new();
io::stdin().read_line(&mut name_line).unwrap();
let name = name_line.trim();
if !quiet {
println!("{}", greeting(name));
}
 
let mut line = String::new();
loop {
line.clear();
let bytes = io::stdin().read_line(&mut line).unwrap();
if bytes == 0 {
break; // no more input: the keyboard was closed
}
let message = line.trim();
match message {
"" => {} // nothing typed: nothing to answer
"/help" => println!("bot: {}", HELP),
"/quit" => {
println!("bot: bye, {}!", name);
break;
}
"/again" => {
if last.is_empty() {
println!("bot: nothing to repeat yet");
} else {
println!("bot: {}", reply(&last));
}
}
"/history" => {
if transcript.is_empty() {
println!("bot: nothing said yet");
} else {
print!("{}", transcript);
}
}
other => {
if is_command(other) {
println!("bot: I don't know the command {}. Try /help.", other);
} else {
messages_seen += 1;
let said = String::from(other);
let answer = reply(&said);
record(&mut transcript, "you", &said);
record(&mut transcript, "bot", &answer);
println!("bot: {}", answer);
last = said;
}
}
}
}
println!("messages so far: {}", messages_seen);
}

Download this version (zip)Unzip, then cargo run inside the folder.

Try itYour turn: write record in Chatterbox

This is Chatterbox v0.4 with the body of record replaced by todo!(). Make it add who, then a colon and a space, then text, then a newline, to the end of the borrowed log. It returns nothing: the change is made to the owner's String, the transcript in main.

This is Chatterbox v0.4 with the body of record replaced by todo!(). Make it add who, then a colon and a space, then text, then a newline, to the end of the borrowed log. It returns nothing: the change is made to the owner's String, the transcript in main.

// Chatterbox: a small chat program, built one lesson at a time.
use std::io;
 
/// What the bot is called. A constant: fixed for the whole program.
const BOT: &str = "Chatterbox";
/// The version as a pair of numbers: (major, minor).
const VERSION: (u32, u32) = (0, 4);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /again, /history, /quit";
 
/// The first line Chatterbox prints.
fn banner() -> String {
format!("{} v{}.{}", BOT, VERSION.0, VERSION.1)
}
 
/// The greeting, with a name filled in.
fn greeting(name: &str) -> String {
let mut text = format!("Hi {}! I'm {}.", name, BOT);
text.push_str(" Ask me anything.");
text
}
 
/// True when the text is a command: it starts with a slash.
/// It only looks at the text, so it borrows it (&str) and never owns it.
fn is_command(text: &str) -> bool {
text.starts_with('/')
}
 
/// Add one line to the transcript. `log` is borrowed mutably (&mut):
/// this function may change it, and nobody else can touch it meanwhile.
fn record(log: &mut String, who: &str, text: &str) {
todo!()
}
 
/// What the bot says back to one message.
fn reply(message: &str) -> String {
if message.len() > MAX_LEN {
format!("that is too long (the limit is {} bytes)", MAX_LEN)
} else if message.ends_with('?') {
String::from("Good question! I can only echo for now. Ask me again in chapter 9.")
} else {
format!("you said: {}", message)
}
}
 
fn main() {
let mut messages_seen: u32 = 0;
let quiet = false; // true skips the greeting
let mut last = String::new(); // the last thing you said, for /again
let mut transcript = String::new(); // everything said so far
 
println!("{}", banner());
println!("What should I call you?");
let mut name_line = String::new();
io::stdin().read_line(&mut name_line).unwrap();
let name = name_line.trim();
if !quiet {
println!("{}", greeting(name));
}
 
let mut line = String::new();
loop {
line.clear();
let bytes = io::stdin().read_line(&mut line).unwrap();
if bytes == 0 {
break; // no more input: the keyboard was closed
}
let message = line.trim();
match message {
"" => {} // nothing typed: nothing to answer
"/help" => println!("bot: {}", HELP),
"/quit" => {
println!("bot: bye, {}!", name);
break;
}
"/again" => {
if last.is_empty() {
println!("bot: nothing to repeat yet");
} else {
println!("bot: {}", reply(&last));
}
}
"/history" => {
if transcript.is_empty() {
println!("bot: nothing said yet");
} else {
print!("{}", transcript);
}
}
other => {
if is_command(other) {
println!("bot: I don't know the command {}. Try /help.", other);
} else {
messages_seen += 1;
let said = String::from(other);
let answer = reply(&said);
record(&mut transcript, "you", &said);
record(&mut transcript, "bot", &answer);
println!("bot: {}", answer);
last = said;
}
}
}
}
println!("messages so far: {}", messages_seen);
}

Hidden tests (3): empty_text_still_gets_a_line keeps_what_was_there records_one_exchange

This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
What does &mut let a borrower do that & does not?Reveal
Change the value. It still does not own it, so nothing is cleaned up when the borrower finishes.
What is the rule about how many borrows can exist at once?Reveal
Any number of & readers, or exactly one &mut editor. Never a reader and an editor, and never two editors.
Which error do you get for two &mut at once?Reveal
E0499, cannot borrow as mutable more than once at a time.

That is lesson 4.5. Tick it off so the course remembers where you are.

Next: 4.6 Parts of a value →

Questions people ask

What is &mut in Rust?

&mut makes a mutable reference: a loan that lets the borrower change the value without owning it. The value itself must be declared with let mut.

What does error E0499 mean in Rust?

You made a second changeable reference to a value while the first one is still going to be used. Let the first one finish before making the next.

Why can Rust only have one mutable reference at a time?

Two editors of the same value could each change it without knowing what the other did. Allowing only one editor at a time rules that whole kind of bug out before the program runs.

How do I let a function change a String it does not own?

Give the function a parameter of type &mut String, and call it with &mut and the variable name. The variable must have been made with let mut.

Learn Rust by building a chat app · Lesson 4.5 · every compiler message above is real output from rustc 1.99.0 (b940084d7 2026-09-28) (edition 2024) · Vibe Engines · 2026