Mutable References
In this page:
let mut value = data;
let r = &mut value;
*r = new_value;
fn name(param: &mut Type) {}
Creating a Mutable Reference
Writing &mut value creates a reference that is allowed to modify the data it points to. The variable being referenced must itself have been declared with mut.
Example: Creating a Mutable Reference
// Define the function `add_exclamation` taking `s`
fn add_exclamation(s: &mut String) {
s.push_str("!");
}
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `message`, initialized to `String::from("Hello")`
let mut message = String::from("Hello");
add_exclamation(&mut message);
// Print "{}" to the console, substituting in `message` (with a trailing newline)
println!("{}", message);
}
Login to try C/C++/Java/PHP code in the editor
Only One Mutable Reference at a Time
Rust enforces that at most one mutable reference to a value can exist within a given scope, preventing two pieces of code from unexpectedly changing the same data at once.
r1's scope ends before r2 is created -- that's what makes this compile.Example: Only One Mutable Reference at a Time
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `count`, initialized to `5`
let mut count = 5;
{
// Declare an immutable variable `r1`, set to `&mut count`
let r1 = &mut count;
*r1 += 1;
}
// Declare an immutable variable `r2`, set to `&mut count`
let r2 = &mut count;
*r2 += 1;
// Print "count = {}" to the console, substituting in `count` (with a trailing newline)
println!("count = {}", count);
}
Login to try C/C++/Java/PHP code in the editor
Cannot Mix Mutable and Immutable References
You cannot hold a mutable reference at the same time as any immutable references to the same value, since a reader could otherwise see the data change unexpectedly mid-read.
Example: Cannot Mix Mutable and Immutable References
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `value`, initialized to `10`
let mut value = 10;
{
// Declare an immutable variable `readable`, set to `&value`
let readable = &value;
// Print "Read before mutation: {}" to the console, substituting in `readable` (with a trailing newline)
println!("Read before mutation: {}", readable);
}
// Declare an immutable variable `writable`, set to `&mut value`
let writable = &mut value;
*writable += 5;
// Print "After mutation: {}" to the console, substituting in `value` (with a trailing newline)
println!("After mutation: {}", value);
}
Login to try C/C++/Java/PHP code in the editor
Dereferencing to Modify
To change the value behind a mutable reference, use the dereference operator * to access the underlying data directly.
Example: Dereferencing to Modify
// Define the function `double` taking `n`
fn double(n: &mut i32) {
*n *= 2;
}
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `x`, initialized to `7`
let mut x = 7;
double(&mut x);
// Print "x is now {}" to the console, substituting in `x` (with a trailing newline)
println!("x is now {}", x);
}
Login to try C/C++/Java/PHP code in the editor
- Trying to create two mutable references to the same value in the same scope, which the borrow checker forbids.
- Mixing a mutable reference and an immutable reference to the same value at the same time.
- Forgetting
muton both the original variable and the reference itself when creating a mutable reference.
- A mutable reference is written
&mut valueand allows modifying the borrowed data. - Only one mutable reference to a particular value can exist at a time within its scope.
- You cannot have a mutable reference and any immutable references active at the same time.
- The original variable must itself be declared with
mutbefore it can be mutably borrowed.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: