The error that confuses almost every Rust beginner
You write three lines of Rust, hit compile, and get an error about a borrow of a moved value. The code looks harmless, so the error feels unfair.
fn main() {
let s1 = String::from("hello");
let s2 = s1;
println!("{}", s1);
}
The house key
Think of it like handing someone your only house key. Once you give it away, you cannot also use it yourself.
That is what let s2 = s1 does. A String owns its text in memory, and Rust allows only one owner at a time. After the assignment, s2 holds the key and s1 holds nothing. When the next line tries to print s1, the compiler stops you, because s1 no longer owns anything.
Why Rust does this
Other languages would quietly copy the text or let both names point at the same memory. Copying costs time, and sharing causes bugs when one name frees the memory while the other still uses it. Rust avoids both by tracking a single owner and checking it before the program ever runs.
Two ways to fix it
If you need both variables to own their own text, make a real copy.
fn main() {
let s1 = String::from("hello");
let s2 = s1.clone();
println!("{}", s1);
println!("{}", s2);
}
Clone makes a full copy, so each variable owns separate data and both stay valid.
If you only need to read the text, borrow it instead of taking it.
fn main() {
let s1 = String::from("hello");
let s2 = &s1;
println!("{}", s1);
println!("{}", s2);
}
Now s2 is only a reference. The key never left s1, so s1 stays valid.
A habit that helps
Whenever a move error appears, ask who owns the value right now. Most of these errors disappear once you can answer that.
I built a small tool called BorrowFix that explains 20 common Rust compiler errors this way, with an analogy first, then the real error, the concept and the fix. You can try it here: https://borrowfix-smoky.vercel.app
Which Rust error confused you the most when you were learning? I would like to add it next.
Top comments (0)