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.
$ cargo run
you: hi
bot: helloRead 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.
Step through the program. Solid arrows are ownership; dashed arrows are borrows. Use ← → or the slider.
- Line 6. The program starts in main.
- Line 7. An empty String is made. log owns it, and it is declared mut, which means its owner allows it to change.
- 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 Stringborrowslog. - Line 2. push_str adds the text. The change happens to the owner's String, since the borrower points straight at it.
- Line 3. push adds one character, the newline written \n, so the next line will start on a line of its own.
- Line 4. The function ends and the loan is over. Nothing is cleaned up, because the borrower never owned the String.
- 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 Stringborrowslog. - Line 2. push_str adds bot: hello after the newline that is already there.
- Line 3. And a newline to end that line too.
- Line 4. The second loan ends the same way, with nothing cleaned up.
- 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: histdout: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.
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
Each bar is one borrow, drawn from its first use to its last. Scrub the line to see what is alive.
log: owner — owner, lines 1–7log: a = &mut log — mutable borrow, lines 3–5log: b = &mut log — mutable borrow, lines 4–6
This is the exact output of the real compiler. Toggle the English, then pick a fix and see what actually happens.
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 →
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.first mutable borrow occurs herepoints at line 3, whereawas made.second mutable borrow occurs herepoints at line 4, wherebtried to start.first borrow later used herepoints 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>&mut log</code>.
What does this print?
642
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.
Sam hello how are you? /history /quit
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)
Download this version (zip)Unzip, then cargo run inside the folder.
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.
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.
Say it out loud, then reveal
What does &mut let a borrower do that & does not?Reveal
What is the rule about how many borrows can exist at once?Reveal
Which error do you get for two &mut at once?Reveal
That is lesson 4.5. Tick it off so the course remembers where you are.
Go deeper
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.