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.)
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.
Step through the program. Solid arrows are ownership; dashed arrows are borrows. Use ← → or the slider.
- Line 5. The program starts in main.
- Line 6. The message is made. msg owns it: msg holds the one key.
- 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.
- Line 2. archive prints the message it now owns. stdout:
[archived] /help - Line 3. archive ends. Its msg was the owner and goes out of scope, so the text is cleaned up here.
- 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.
This is the exact output of the real compiler. Toggle the English, then pick a fix and see what actually happens.
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 →
borrow of moved value: `msg`: you usedmsgon line 8, but its key is gone.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.- The two marked places are the whole story:
value moved hereon line 7 andvalue borrowed here after moveon line 8. 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.
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.
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.
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:
reply(&said)answers it. The&lendssaidtoreplyfor a moment without giving the key away: it is the second fix from the coach above, and the next lesson is all about it.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 withlet keep = msg;). From this line on,saidowns 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.
Sam hello /again /quit
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)
Download this version (zip)Unzip, then cargo run inside the folder.
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.
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.
Say it out loud, then reveal
What happens to a String when you pass it to a function by value?Reveal
Name two ways to fix error E0382 that cost nothing.Reveal
Why can you use an i32 after passing it to a function?Reveal
That is lesson 4.3. Tick it off so the course remembers where you are.
Go deeper
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.