🔗 References & Borrowing in Rust


📌 What Is a Reference?

A reference lets you borrow a value without taking ownership.

rust
Loading…

&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.

rust
Loading…

You can create multiple immutable references at the same time:

rust
Loading…

🛠️ Mutable References

If you want to change a borrowed value, you need a mutable reference using &mut:

rust
Loading…

👉 Rules for mutable references:

  • You can have only ONE mutable reference to a piece of data at a time.

❌ This won't work:

rust
Loading…

Rust enforces this at compile-time to prevent data races.

✅ But you can use a mutable reference after an earlier one is done:

rust
Loading…

🚫 Dangling References

Rust does not allow dangling references — that is, references to data that no longer exists:

rust
Loading…

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!