References and Borrowing Explained
Learn about references and borrowing, allowing multiple parts of your code to access data without taking ownership, safely.
What are References?
In Rust, variables own their data. But what if you need to let other parts of your code look at or even change that data without taking ownership?
That's where references come in! A reference is like a pointer to a value, but with strict rules enforced by the Rust compiler.
Think of it as looking at something through a window instead of owning the item itself.
Your First Reference
We create a reference using the & operator. This creates a non-owning pointer to a value. Let's see it in action:
fn print_length(s: &String) {
println!("The length is: {}", s.len());
}
fn main() {
let message = String::from("Hello, CoddyKit!");
print_length(&message); // Pass a reference
println!("Original message still here: {}", message);
}All lessons in this course
- Understanding Rust's Ownership Model
- References and Borrowing Explained
- Lifetimes for Safe References