0PricingLogin
Learn Rust Coding · Lesson

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

  1. Understanding Rust's Ownership Model
  2. References and Borrowing Explained
  3. Lifetimes for Safe References
← Back to Learn Rust Coding