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.3 · 10 min

Handing over the key

Chatterbox wants a new command, /again, and for that it must keep your last message after the loop moves on. Keeping it means handing the key to a new owner, and once a key is handed over the old name cannot use it. That is not a bug, and this lesson is about reading the compiler error that tells you so.

Adds to Chatterbox/again: your last message is handed over to be kept.

Compiler errors you will meet E0382

Giving the key away

In lesson 4.2 every value had one key. What if a function needs the message? There are two honest answers: give it the key, or lend it. Lending is the next lesson. This one is giving, which Rust calls a move.

Start with a tiny program, separate from Chatterbox: an archive function that wants to keep a message for itself. It takes a String, which is the whole value and its key. Read the program, then guess what the compiler thinks of it. (Chatterbox's own move comes at the end of the lesson.)

PredictArchive a message, then say it again
fn archive(msg: String) {
println!("[archived] {msg}");
}
 
fn main() {
let msg = String::from("/help");
archive(msg);
println!("you said: {msg}");
}

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

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

It does not compile: E0382. Calling archive(msg) hands the key to the function. When archive ends, the message is cleaned up. The next line asks for a message that no longer exists, so the compiler refuses.

error[E0382]: borrow of moved value: `msg`
 --> src/main.rs:8:26
  |
6 |     let msg = String::from("/help");
  |         --- move occurs because `msg` has type `String`, which does not implement the `Copy` trait
7 |     archive(msg);
  |             --- value moved here
8 |     println!("you said: {msg}");
  |                          ^^^ value borrowed here after move
  |
note: consider changing this parameter type in function `archive` to borrow instead if owning the value isn't necessary
 --> src/main.rs:1:17
  |
1 | fn archive(msg: String) {
  |    -------      ^^^^^^ this parameter takes ownership of the value
  |    |
  |    in this function
help: consider cloning the value if the performance cost is acceptable
  |
7 |     archive(msg.clone());
  |                ++++++++

Watch the key change hands

The compiler will never run this program, so the stage below is a thought experiment: it plays the program as if it were allowed to run, to show what would happen and why the compiler refuses. Step through it. At the call, the arrow does not stretch to the function and leave a copy behind. It moves: the old name keeps its place on the page but holds nothing.

Ownership Stagearchive(msg) moves the String into the function

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

fn archive(msg: String) {
println!("[archived] {msg}");
}
 
fn main() {
let msg = String::from("/help");
archive(msg);
println!("you said: {msg}");
}
  1. Line 5. The program starts in main.
  2. Line 6. The message is made. msg owns it: msg holds the one key.
  3. Line 7. archive(msg) pushes a frame for archive and hands the key over: the String's 24 bytes (pointer, length, capacity) are copied into archive's msg, and the text on the heap does not move at all. main's msg is marked moved, because two owners of one block would mean two hand-backs.
  4. Line 2. archive prints the message it now owns. stdout: [archived] /help
  5. Line 3. archive ends. Its msg was the owner and goes out of scope, so the text is cleaned up here.
  6. Line 8. If the program were allowed to run, main would now ask for msg, but its key was given away on line 7 and the text is already gone. This is the step the compiler sees coming: it refuses to build the program with E0382, so in reality none of these steps ever run.

Reading the error

Now ask the compiler directly. Below is what it prints, and a plain-words reading of each part. The error looks long, but it is telling a three-line story: where the value was made, where the key was handed away, and where you tried to use it anyway.

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 archive(msg: String) {
println!("[archived] {msg}");
}
 
fn main() {
let msg = String::from("/help");
archive(msg);
println!("you said: {msg}");
}
error[E0382]: borrow of moved value: `msg`
 --> src/main.rs:8:26
  |
6 |     let msg = String::from("/help");
  |         --- move occurs because `msg` has type `String`, which does not implement the `Copy` trait
7 |     archive(msg);
  |             --- value moved here
8 |     println!("you said: {msg}");
  |                          ^^^ value borrowed here after move
  |
note: consider changing this parameter type in function `archive` to borrow instead if owning the value isn't necessary
 --> src/main.rs:1:17
  |
1 | fn archive(msg: String) {
  |    -------      ^^^^^^ this parameter takes ownership of the value
  |    |
  |    in this function
help: consider cloning the value if the performance cost is acceptable
  |
7 |     archive(msg.clone());
  |                ++++++++

E0382 in the compiler error atlas →

  1. borrow of moved value: `msg`: you used msg on line 8, but its key is gone.
  2. move occurs because `msg` has type `String`, which does not implement the `Copy` trait (a trait is a named ability; you meet traits properly in chapter 8): a String is not cheap to duplicate, so passing it hands over the key instead of making a second one.
  3. The two marked places are the whole story: value moved here on line 7 and value borrowed here after move on line 8.
  4. help: consider changing this parameter type in function `archive` to borrow instead: the compiler is already pointing at the other answer, which you meet next lesson.

Fixes that were compiled for real

  • Use it first, hand it over last — compiles. The key moves on the last line, after every use. Free, and often the simplest fix.
  • Lend it instead: take &str — compiles. archive only reads the message, so it never needed the key. The & means "look, do not take". The next lesson is all about this.
  • Make a second copy with .clone() — compiles, with a cost. It compiles because there are now two values with two keys. It also copies all the text. Fine for a small message, wasteful in a loop. Treat it as a choice, not a reflex.
  • Trap: copy the name first — still E0382. Writing <code>let keep = msg;</code> does not duplicate anything. It moves the key to <code>keep</code>, so msg is gone again. A new name is not a new key.

Why numbers do not move

A whole number is a few bytes that describe themselves completely: lesson 4.1 showed a u32 living entirely in its frame slot. Duplicating one is free and leaves no heap block to clean up. Rust marks such types Copy: handing one over leaves you holding an identical one. i32, bool, single characters (a char is one letter in single quotes) and decimal numbers like f64 are Copy. String is not, and the reason is the stage above. Copying a String's 24 bytes would copy only the pointer, length and capacity, not the text, so two owners would hold the key to one heap block, and that block would be handed back twice. Copy is only for types whose bytes in the frame are the whole value. A real second String, with its own block and its own copy of the text, is what .clone() makes, and you have to ask for it.

PredictThe same shape with a number
fn spend(tokens: i32) {
println!("spent {tokens}");
}
 
fn main() {
let tokens = 50;
spend(tokens);
println!("left {tokens}");
}

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

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

It compiles and runs. An i32 is Copy. spend received its own copy and the original is untouched, so the next line is fine.

Try itYour turn: take the key and give back a result

A warm-up, separate from Chatterbox. Make shout take the whole String, add ! to it and return it. The caller keeps working with what comes back.

A warm-up, separate from Chatterbox. Make shout take the whole String, add ! to it and return it. The caller keeps working with what comes back.

fn shout(mut msg: String) -> String {
// add a ! to the end and hand the String back
msg
}
 
fn main() {
let msg = String::from("hi");
let loud = shout(msg);
println!("{loud}");
}

Hidden tests (3): adds_a_bang stacks_up works_on_empty

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

Chatterbox v0.4: /again

Chatterbox gets a new command. /again repeats the answer to the last thing you said, and says nothing to repeat yet if you have not said anything. To do that, the program must hold on to your last message after the loop turn that read it is over.

The message arrives in the catch-all arm of the match as other, and other cannot do that job. It is a &str looking into line's heap block (lesson 4.1), and line is cleared at the start of every turn. That is the honest reason for a copy here: the text has to outlive the block it was read into. So the program makes a String of its own with let said = String::from(other);: a new heap block holding a copy of the text, and said owns it. Then, in this order:

  1. reply(&said) answers it. The & lends said to reply for a moment without giving the key away: it is the second fix from the coach above, and the next lesson is all about it.
  2. last = said; hands the key over. A plain = moves a String exactly like passing it to a function does (the trap in the coach showed the same thing with let keep = msg;). From this line on, said owns nothing.

last was made before the loop with let mut last = String::new();, so it lives in main's frame across every turn, and /again reads it. When last receives a new key, the block it held before is handed back first, so old messages do not pile up.

The match from chapter 3 keeps its shape and gains one arm, "/again" =>, placed before the catch-all so the catch-all never sees it. Inside the arm, an if (lesson 3.1) asks last.is_empty(): nothing said yet gets nothing to repeat yet, otherwise reply(&last) answers the kept message again, lending it the same way. Commands are still never counted: only the catch-all adds to messages_seen. The help text grows to commands: /help, /again, /quit.

Chatterbox v0.4 after lesson 4.3: the whole program (green lines are new in this lesson)
You type
Sam
hello
/again
/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: you said: hello
bot: bye, Sam!
messages so far: 1
Show the whole program (open it after you have tried the exercise below: it contains the answer)
src/main.rs14 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
}
 
/// 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 => {
messages_seen += 1;
// `line` is cleared on the next turn, so keep a copy that we own.
let said = String::from(other);
println!("bot: {}", reply(&said));
last = said; // use it first, hand the key over last: `said` is done
}
}
}
println!("messages so far: {}", messages_seen);
}
Cargo.toml1 new line
[package]
name = "chatterbox"
version = "0.4.0"
edition = "2024"
 
[dependencies]

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

Try itYour turn: hand the key over last in Chatterbox

This is Chatterbox v0.4 with two lines swapped. The key is handed to last first, and only then is said lent to reply, so the program does not compile: run it and you get E0382. Fix it the way the first fix in the coach did, without .clone(): use it first, hand it over last. The hidden tests check the reply rules, and they cannot run at all until the program compiles.

This is Chatterbox v0.4 with two lines swapped. The key is handed to last first, and only then is said lent to reply, so the program does not compile: run it and you get E0382. Fix it the way the first fix in the coach did, without .clone(): use it first, hand it over last. The hidden tests check the reply rules, and they cannot run at all until the program compiles.

// 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
}
 
/// 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 => {
messages_seen += 1;
// `line` is cleared on the next turn, so keep a copy that we own.
let said = String::from(other);
last = said; // use it first, hand the key over last: `said` is done
println!("bot: {}", reply(&said));
}
}
}
println!("messages so far: {}", messages_seen);
}

Hidden tests (3): help_lists_again the_kept_message_gives_the_same_answer a_message_is_echoed

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 happens to a String when you pass it to a function by value?Reveal
The key moves to the function. The old name can no longer be used.
Name two ways to fix error E0382 that cost nothing.Reveal
Use the value before handing it over, or lend it with a reference so the function never takes the key.
Why can you use an i32 after passing it to a function?Reveal
It is Copy: the function got its own duplicate, so the original key still exists.

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

Next: 4.4 Borrowing →

Questions people ask

What does borrow of moved value mean in Rust?

It is error E0382. You gave a value away, for example by passing a String to a function, and then tried to use it again. The old name no longer owns anything.

What is a move in Rust?

A move hands a value from one owner to another. The text itself is not copied; only the ownership travels, and the old name can no longer be used.

Should I just use clone() to fix move errors?

Sometimes, but it makes a full copy, which costs time and memory. Often it is better to use the value before handing it over, or to lend it with a reference.

Which Rust types are Copy?

Small values that are cheap to duplicate, such as whole numbers, decimal numbers, bool and char. String is not Copy: its text lives in a separate heap block, so copying its 24 bytes would give two owners of one block, which would then be freed twice.

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