Back to course

References & Borrowing

Rust for Systems & Web3 Security

Borrowing Data

What if you want to use a value without taking ownership? You use references (&).

rust fn calculate_length(s: &String) -> usize { s.len() }

The Rules of Borrowing

  1. You can have either one mutable reference (&mut T) OR any number of immutable references (&T) at the same time.
  2. References must always be valid.

This system prevents Data Races at compile time, which is essential for multi-threaded systems and secure blockchain nodes.