One Owner at a Time
Hereβs the idea Rust is most famous for: ownership. It sounds fancy, but itβs something you already understand from real life. Think about your phone β you own it. Right now, youβre the one holding it. In Rust, every value works the same way: it has one owner at a time. π±
One owner at a time
When you write let message = String::from("Hello!");, the variable message becomes the
owner of that text. A String is a piece of text the program stores in memory.
Giving it away = βmovingβ
What happens if you hand your phone to a friend? Now they have it, and you donβt. Rust calls this a move. After you move a value to a new owner, the old name canβt use it anymore.
If you tried to use the old name, Rust would stop you at compile time and explain that the value was moved. Thatβs Rust protecting you from a whole class of bugs. π‘οΈ
When we passed message into send, ownership moved inside the function. After that,
message no longer owns anything, so we donβt use it again.
Numbers are different
Small, simple values like numbers donβt get moved β they get copied. A number is more like a fact you can share: if you tell a friend your score, you both know it. So both variables keep working.
String get moved.
Small ones like numbers get copied. Either way, Rust keeps everything safe. π¦
"Hello!" to your own message and press
βΆ Run. Watch the value travel into the function.
Quick quiz
After you move a String to a new owner, can you still use the old name?
Correct! A move hands the value to a new owner, so the old name can no longer use it. π±
String to a new owner is
a move (the old name stops working), and small values like numbers are
copied instead. Next up: how to lend a value to a function and get it back β
that's borrowing! π€