Hoi hoi! 😸
Happy Friday! Let's learn a tiny bit of Rust! 😸🍻
No complicated architecture. No giant diagrams. Just a cat, a crab, and a little bit of ownership.
Grab a beer! 🍺
🐈 Ownership::This Is My Cat!
Rust has three simple ownership rules:
- Every value has an owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped.
Let's adopt a cat!
let a = String::from("cat"); let b = a; println!("{b}"); 📦 Move::Wait... Where's My Cat?!
What happens if we try to use a again?
println!("{a}"); // ❌ Compile error! WHAT?! WHERE IS MY CAT?! 🙀
Ownership moved from a to b.
Sorry, a. That's not your cat anymore. 😿
Rust remembers. Rust never forgets. 🦀
🤝 Borrowing::Can I Pet Your Cat?
What if we just want to borrow a value without taking ownership?
We can use a reference (&).
let a = String::from("cat"); let b = &a; println!("{b}"); println!("{a}"); WOW! Both work! 😸
a still owns the value. b is just borrowing it.
You can pet my cat, but you can't take it home. 😼
✏️ MutableBorrowing::The Cats Are Multiplying!
A shared reference (&) doesn't let us modify the borrowed String.
But a mutable reference (&mut) does!
let mut a = String::from("cat"); let b = &mut a; b.push_str(" and another cat"); println!("{a}"); Output 👇
cat and another cat Oh no.
The cats are multiplying. 🐈🐈
🦀 BorrowChecker::One Human at a Time!
Multiple humans can pet the same cat.
let cat = String::from("cat"); let a = &cat; let b = &cat; println!("{a} {b}"); // ✅ Everyone is happy. The cat gets extra attention. 😸
But what if two humans try to brush the same cat at once?
let mut cat = String::from("cat"); let a = &mut cat; let b = &mut cat; // ❌ Compile error! a.push_str(" is fluffy"); b.push_str(" is SUPER fluffy"); Rust::ABSOLUTELY NOT. 🦀💢
So here's the rule:
-
&— Many humans can borrow the cat for reading. -
&mut— Only one human can borrow the cat for modification, with no other active borrows.
Want to brush the cat? Wait until everyone else is done borrowing it!
The crab is just trying to keep our cats safe. 🐈💚
🍪 Summary::One Little Byte at a Time
-
Ownership-> This is my cat. -
Move-> It's your cat now. -
&-> You can pet my cat. -
&mut-> You can brush my cat, but one human at a time. -
BorrowChecker-> The angry crab protecting our cats. 🦀
That's it for today's Cozy Bytes!
Rust looks scary sometimes, but we don't have to learn everything at once.
One little byte at a time. 😸💚
Happy Friday! 🍻