Menu

1 / 3

Cozy Bytes 🍺 | Rust::Who Owns the Cat? πŸˆπŸ¦€

DEV Community: rustΒ·nyaomaruΒ·10 days ago
#UKJUjKNT
#devtorust#devto#dev#enter#exit
Long article (585 words) β€” no AI summary yet.
Reading 0:00
15s threshold

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}" ) ;

Enter fullscreen mode

Exit fullscreen mode

πŸ“¦ Move::Wait... Where's My Cat?!

What happens if we try to use a again?

println! ( "{a}" ) ; // ❌ Compile error!

Enter fullscreen mode

Exit fullscreen mode

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!…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.