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.4 · 11 min

Lending the key

Most functions only want to look at a message, not own it. Rust lets you lend a value with &, and the owner keeps the key. This lesson also shows the one thing a lender cannot do while the loan is out.

Adds to ChatterboxUnknown commands get a helpful answer from a borrowing function.

Compiler errors you will meet E0502

Lending instead of giving

You have seen the key move (lesson 4.3). Handing a key over every time a function wants to look at something would be exhausting: you would have to get it back each time. The second option is to lend it. The owner keeps the key. The borrower gets a reference, written with &, which lets it look but not take, and certainly not clean up.

Look at how little changes in the code. The function says what it needs with &str ("a borrowed piece of text"), and the caller says it is lending with &msg. (to_uppercase() is a text method that builds a new String with every letter in capitals.)

shout borrows the message; main keeps it
fn shout(text: &str) -> String {
text.to_uppercase()
}
 
fn main() {
let msg = String::from("hello");
let loud = shout(&msg);
println!("{loud} / {msg}");
}
$ cargo run
HELLO / hello

The last line uses msg after shout has run. Under the rule from lesson 4.3 that would have been an error. It is fine here because shout only held a borrow. The key never left msg.

Ownership Stageshout(&msg) borrows; main keeps ownership

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

fn shout(text: &str) -> String {
text.to_uppercase()
}
 
fn main() {
let msg = String::from("hello");
let loud = shout(&msg);
println!("{loud} / {msg}");
}
  1. Line 5. The program starts in main.
  2. Line 6. msg is made and owns the text.
  3. Line 7. shout(&msg) pushes a frame for shout and lends msg. Its parameter text is a &str: 16 bytes, a pointer and a length aimed at msg's heap text (the dashed arrow). It points at the text but owns nothing; msg still holds the key. text: &str borrows bytes 0..5 of msg.
  4. Line 2. shout reads the borrowed text and builds a brand new String, HELLO, that it will hand back by return.
  5. Line 3. shout ends. The loan is over, and because the borrower never owned the text, nothing is cleaned up. The new String's key goes to loud.
  6. Line 8. Both names are valid, so this prints HELLO / hello. stdout: HELLO / hello

What a borrow costs you

A loan has one condition, and it is a natural one. While somebody is looking at a value, the owner may not change it. Lesson 4.1 showed why in pictures: when a String grows, it may move its text to a bigger heap block and hand the old one back. A borrower still pointing at the old block would be reading memory that is no longer the String's. So long as there are shared borrowers, the room is read-only. You can have as many lookers as you like, but no editors.

How long is "while"? From the line where the reference is made to the last line where it is used. Not to the end of the block. Read this program and predict.

PredictChange the text while a reference is still used
fn main() {
let mut transcript = String::from("you: hi");
let view = &transcript;
transcript.push_str(" there");
println!("{view}");
}

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

  • It compiles and runs
  • Compile error E0502
  • It compiles, then panics
Reveal the answer

It does not compile: E0502. view is a borrow of transcript, and it is used again on the last line. push_str in between wants to change the text, which is not allowed while the loan is live.

error[E0502]: cannot borrow `transcript` as mutable because it is also borrowed as immutable
 --> src/main.rs:4:5
  |
3 |     let view = &transcript;
  |                ----------- immutable borrow occurs here
4 |     transcript.push_str(" there");
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("{view}");
  |                ---- immutable 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 transcript = String::from("you: hi");
let view = &transcript;
transcript.push_str(" there");
println!("{view}");
}
  • transcript: owner — owner, lines 1–6
  • transcript: view = &transcript — shared borrow, lines 3–5
  • transcript: push_str (changes it) — mutable borrow, lines 4–4

Each row is a value and each bar is a stretch of lines. The blue bar is the loan, drawn from first use to last use. The change on line 4 lands inside it, and that overlap is the error. Now the compiler's own words.

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 transcript = String::from("you: hi");
let view = &transcript;
transcript.push_str(" there");
println!("{view}");
}
error[E0502]: cannot borrow `transcript` as mutable because it is also borrowed as immutable
 --> src/main.rs:4:5
  |
3 |     let view = &transcript;
  |                ----------- immutable borrow occurs here
4 |     transcript.push_str(" there");
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("{view}");
  |                ---- immutable borrow later used here

E0502 in the compiler error atlas →

  1. cannot borrow `transcript` as mutable because it is also borrowed as immutable: "mutable" means changing, "immutable" means just looking. You are changing something that is being looked at.
  2. immutable borrow occurs here points at &transcript on line 3: the loan begins.
  3. mutable borrow occurs here points at push_str on line 4: someone tries to change it while the loan is out.
  4. immutable borrow later used here points at line 5: this is the use that keeps the loan alive. Without it there would be no error.

Fixes that were compiled for real

  • Finish looking before you change — compiles. The last use of <code>view</code> is now before <code>push_str</code>, so the loan has ended. Free.
  • Look at transcript itself afterwards — compiles. Drop the reference and print the owner after the change. You are not borrowing it at all anymore.
  • Trap: print both together after the change — still E0502. Printing <code>view</code> next to the owner looks harmless, but <code>view</code> is still used after <code>push_str</code>, so the loan is still out when the change happens. Where the reference is used last is all that counts.

Chatterbox v0.4: an answer for unknown commands

You have been lending since lesson 1.6 without the word for it: greeting(name: &str) and, since lesson 3.1, reply(message: &str) borrow their text. Last lesson main lent said with &said and moved it into last only afterwards. That order works precisely because a loan leaves the key where it was.

This lesson adds one more borrower. is_command(text: &str) -> bool looks at a piece of text and answers whether it starts with a slash. It only looks, so it borrows and never owns. main asks it first thing in the catch-all other => arm of the match: a line that starts with / but fitted none of the command arms above is a command Chatterbox does not know. Instead of echoing it back, Chatterbox now says so and points you at /help, and it does not count it, because commands are never messages. Only a line that is not a command goes on as before: counted, copied into said, answered, and kept for /again.

Order matters again. The arms for /help, /quit and /again come before the catch-all, so the commands Chatterbox knows are taken there and never reach is_command, or they would be called unknown too.

Chatterbox v0.4 after lesson 4.4: the whole program (green lines are new in this lesson)
You type
Sam
/dance
/quit
Chatterbox prints (a real run)
Chatterbox v0.4
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: I don't know the command /dance. Try /help.
bot: bye, Sam!
messages so far: 0
Show the whole program (open it after you have tried the exercise below: it contains the answer)
src/main.rs13 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, /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('/')
}
 
/// 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
 
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));
}
}
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);
println!("bot: {}", reply(&said));
last = said;
}
}
}
}
println!("messages so far: {}", messages_seen);
}

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

Try itYour turn: look without taking, in Chatterbox

This is Chatterbox v0.4 with the body of is_command replaced by todo!(). Write it: it borrows the text and gives back true when the text starts with /. Text has a method starts_with(x) that answers exactly that: true when the text begins with x, and a single character goes in single quotes. Only the very first character counts: a space before the slash means it is not a command.

This is Chatterbox v0.4 with the body of is_command replaced by todo!(). Write it: it borrows the text and gives back true when the text starts with /. Text has a method starts_with(x) that answers exactly that: true when the text begins with x, and a single character goes in single quotes. Only the very first character counts: a space before the slash means it is not a command.

// 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, /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 {
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
 
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));
}
}
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);
println!("bot: {}", reply(&said));
last = said;
}
}
}
}
println!("messages so far: {}", messages_seen);
}

Hidden tests (5): empty_is_not_a_command plain_text_is_not the_owner_keeps_its_string slash_is_a_command a_space_before_the_slash_is_not_a_command

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 & in front of a value do to ownership?Reveal
Nothing. It lends a reference; the owner keeps the key and the value is not cleaned up when the borrower finishes.
How long does a borrow last?Reveal
From the line where the reference is made to the last line where it is used.
Why is changing a value while a shared borrow is still used refused?Reveal
The borrower is reading it. A change could pull the text out from under them, so the compiler gives E0502.

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

Questions people ask

What is borrowing in Rust?

Borrowing means letting code use a value without taking ownership of it. You write & in front of the value, and the owner keeps it and can use it again afterwards.

What is a reference in Rust?

A reference, written with &, points at a value that someone else owns. It lets you read the value, and it never cleans it up.

What does error E0502 mean in Rust?

You tried to change a value while a reference to it is still going to be used. Finish using the reference first, then make the change.

Can I have more than one reference to the same value?

Yes, as many read-only references as you like at the same time. What you cannot do is change the value while any of them is still in use.

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