Course contentsShow
← Rust
Lesson 109 of 1,9102. The Ownership ModelFree lesson

Shared versus Exclusive Borrowing

Manage high-concurrency code by balancing multiple readers against a single writer.

In this lesson, you will learn how Rust uses the rules of shared and exclusive borrowing to prevent data corruption when multiple parts of your code access the same data.

The Rule of Access

In Rust, the compiler enforces a simple but powerful rule: you can have either many people reading your data at the same time, or one person writing to it, but never both at once.

Think of this like editing a shared document. If everyone is allowed to read the document, the information stays consistent for all readers. However, if one person starts changing the text while others are reading, the readers might see incomplete or confusing information. Rust prevents this "data race" at compile time.

Shared Borrowing (&T)

When you create a shared borrow, you are granting "read-only" access. You can have as many of these as you want simultaneously. Because the data cannot change, it is safe for multiple parts of your program to look at it at the same time.

let data = vec![1, 2, 3];
let reader1 = &data; // Shared borrow
let reader2 = &data; // Another shared borrow (perfectly fine!)
println!("Shared access: {} and {}", reader1[0], reader2[0]);

Exclusive Borrowing (&mut T)

When you create an exclusive borrow, you are granting "read-write" access. Rust ensures that if an exclusive borrow is active, no one else can have any other kind of reference to that data. This guarantees that while you are modifying the data, nobody else is reading an inconsistent state.

let mut data = vec![1, 2, 3];
let writer = &mut data; // Exclusive borrow
writer.push(4); 
// If you tried to create a `let reader = &data` here, 
// the compiler would stop you!

Why it Matters

This system allows you to write high-concurrency code without fearing that one function will change a variable while another function is calculating a result based on that same variable. By enforcing these constraints, the compiler acts as a safety guard, ensuring that your data stays stable regardless of how many parts of your program need to access it.

Key Takeaway: You may have as many shared readers as you like, or exactly one exclusive writer, but never both at the same time.