🔗 References & Borrowing in Rust
References let you access data without taking ownership. This is how Rust lets you write safe, fast code—no garbage collector, no memory bugs!
📌 What Is a Reference?
A reference lets you borrow a value without taking ownership.
&s1
creates a reference to s1
, and the function calculate_length
borrows it.
✅ This means the original value isn’t moved, and you can still use it later!
📏 Immutable References (the default)
By default, references are immutable, meaning you can read the data but not change it.
You can create multiple immutable references at the same time:
🛠️ Mutable References
If you want to change a borrowed value, you need a mutable reference using &mut
:
👉 Rules for mutable references:
- You can have only ONE mutable reference to a piece of data at a time.
❌ This won't work:
Rust enforces this at compile-time to prevent data races.
✅ But you can use a mutable reference after an earlier one is done:
🚫 Dangling References
Rust does not allow dangling references — that is, references to data that no longer exists:
The value s
gets dropped at the end of the function. Returning a reference to it would be dangerous, so Rust prevents this entirely. 🛡️
🧠 Summary
&T
= immutable reference (read-only)&mut T
= mutable reference (can modify the value)- Multiple immutable references are allowed
- Only one mutable reference is allowed at a time
- References let you borrow data without taking ownership
- Rust stops you from using invalid or dangling references at compile time
This is one of Rust’s superpowers: you can write fast, safe code without fear of memory bugs 💥🦀
Next up: Slices – where we dive deeper into referencing parts of data!