24
EP1: Rust Ownership for Toddlers
"Rust is too hard to learn," You whined.
"Maybe because you're a toddler?"
๐ก Ownership IS the only big concept in Rust. It is not unique, and C++ has it too. Understand this well.
Repeat after me, "Thou shall be the only one owning a toy."
That's it. Alice has a toy, then Bob snatches it from Alice. Alice no longer has the toy. Bob runs away and gets bullied by Tim, looting the toy. Then Bob has no toy. Tim has the toy.
If you later asked Alice for the toy, she would just cry and slap you on and on, yelling, "Bob took my toy!"
If you asked Bob to get back the toy, he would lash out with a black eye. "Tim has it!"
fn main() {
let alice = String::from("Teddy");
{
/// Bob suddenly shows up and snatches it from Alice.
let bob = alice;
/// "Bob took it!" Alice cried.
println!("Alice, where is the {}", alice);
let tim = bob;
/// "Tim stole it!" Bob lashed out.
println!("Bob, did you take the {} from Alice?", alice);
/// Tim, an alien under a kid skin, eats the bear.
/// Then, Tim and Bob vanishes into ether.
}
/// "Who's Bob?" Alice said, Teddy no longer in her arm.
/// Cue the X-file music...
println!("Alice, did Bob return the {}", alice);
}
Although this may sound confusing, it is pretty simple in the real, physical world. You were just too spoiled by your X language. Here is the hard fact -- You just can't have more of a thing. A piece of data is not made of pixie dust. It is a bunch of electrons making tricks on a couple of latches to spell out enough 0 and 1 digits to make up a piece of data. As real as a teddy bear.
What most languages do is basically telling Alice and Bob to share, which they can on a good day. On a bad one, they are yanking the toy on each end. On the worst, either one might misplace it and the other explodes. This one hip language named after a fat snake takes it too far by buying a duplicate for every toy for Alice, Bob, Tim, and any other kids who want to play with it.
๐ผ Try-sies
Instead of aString::from("Teddy")
, try a string literal "Teddy" or an integer and keep the code. What happens? Use this playground.
Sensibly, in order for Alice to have the toy, Bob (or whoever was owning it) should return the toy to her.
/// mut means I can change what I have later.
let mut alice = Toy("Teddy");
let bob = alice;
let mut tim = bob;
tim = daghan_does_something(tim);
/// "No!" Alice yelled.
println("Did you get the {:?} back, Alice?", alice);
alice = tim;
/// Print just fine!
println("Now, did you get the {:?} back?", alice);
Since Tim eventually returned the toy back to Alice, Alice is happy.
24