🀝
World 4 Β· The Ownership Superpower

Borrowing: Lending Values

Last time, giving a value away meant you didn’t have it anymore. But what if a friend just wants to look at it, and hand it right back? That’s called borrowing, and Rust has a friendly way to do it. 🀝

The Big Idea A reference (written with an &) lets you borrow a value without taking ownership. It's like lending a library book β€” someone reads it, then it still belongs to you.

The little & means β€œborrow”

When you put an & in front of a value, you’re saying β€œhere, take a peek β€” but I still own it.” A function can take &String to look at the words without becoming the owner.

Think of it like this… Lending a book is different from giving it away. With &, a friend borrows it, reads for a bit, and you get it back good as new!

Because we only borrowed name, main still owns it afterward. We can keep using it! πŸŽ‰

Borrowing to change: &mut

Sometimes a borrower doesn’t just look β€” they actually edit what they borrowed. For that, Rust uses &mut, which means β€œborrow it and you may change it.”

The sharing rule

Rust has one simple rule to keep everything tidy: many readers OR one writer at a time.

  • Lots of people can look at the value together (many &). πŸ‘€
  • But only one person can change it at once (one &mut).

This stops two people from editing the same value at the same time and making a mess.

Ferris says: Many can look, but only one can change at a time. That keeps your data β€” and your code β€” safe! πŸ¦€
Try this! In the sparkles box, change " ✨" to " 🌟" and press β–Ά Run. The borrowed value comes back with a new sparkle!

Quick quiz

What does an & reference let you do?

Yes! & borrows β€” you peek at the value, and the owner still keeps it. 🀝

You learned… A reference (&) borrows a value, &mut lets you change what you borrowed, and the rule is many readers OR one writer. Next up: borrowing just a piece of something β€” A Slice of the Pie! πŸ•