Course contentsShow
← Rust
Lesson 206 of 1,9103. Borrowing and ReferencesFree lesson

Shared Read-Only Access

Implement read-only access across different parts of a program while maintaining safety.

In this lesson, you will learn how to safely share data across different parts of your program without granting anyone the power to change it.

The Power of "Shared"

In Rust, you often want to let multiple functions or parts of your code look at the same piece of data at the same time. If you gave everyone "ownership," they could all try to modify or destroy the data, leading to chaos. Instead, Rust allows Shared Read-Only Access using immutable references.

When you create an immutable reference (using the & symbol), you are essentially saying: "You can look at this, but you are not allowed to touch it." Because the compiler knows no one can modify the data through these references, it allows as many of them as you want to exist simultaneously.

Putting it into practice

Imagine you have a large configuration struct that several different functions need to read. Instead of copying the data or moving it around, you simply pass a reference:

struct Config {
    theme: String,
}

fn print_theme(config: &Config) {
    println!("Current theme: {}", config.theme);
}

fn main() {
    let my_config = Config { theme: String::from("Dark Mode") };

    // We can share read-only access with multiple functions
    print_theme(&my_config);
    print_theme(&my_config);
}

In this example, print_theme accepts &Config. Because it is an immutable reference, the compiler guarantees that print_theme cannot change my_config.theme. Because the compiler has this guarantee, it doesn't matter how many times you call print_theme; the data remains safe and consistent.

Why this matters for safety

This pattern is the bedrock of Rust’s safety. By enforcing "read-only" status, Rust prevents data races, where one part of your code might be reading a value while another part is busy changing it. If you try to modify the data while these shared references exist, the Borrow Checker will stop you immediately. You get the efficiency of sharing the same memory location, combined with the safety of knowing that the data is "locked" from changes while it is being viewed.

Key Takeaway: Shared read-only access allows multiple parts of your program to inspect data simultaneously without the risk of accidental modification or memory inconsistency.