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. π€
&) 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.
&, 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.
" β¨" 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. π€
&) 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! π