There are two types of borrowing in Rust – mutable and shared borrowing – and they involve references.
Rust Mutable Borrowing
Using sample codes, Mutable Borrowing in Rust means the owner passes the variable’s ownership to a function but making the variable open to value change. The function definition must specify the parameter with &mut before the type. For instance, line 1 has this parameter definition – v: &mut i32. On the other hand, codes that call the function must provide a mutable variable using the &mut specified before the variable name.
Example 1 – Modify Integer Value
1 2 3 4 5 6 7 8 9 10 11 | fn mutable_borrow_i32(v: &mut i32) { *v = 100; } fn main() { let mut tmp:i32 = 1; println!("original = {}", tmp); mutable_borrow_i32(&mut tmp); println!("modified = {}", tmp); } |
This example outputs the following.
1 2 | original = 1 modified = 100 |
Example 2 – Modify Vect Contents
1 2 3 4 5 6 7 8 9 10 11 12 | fn mutable_borrow_vec(v: &mut Vec<String>) { v.push("Another string".to_string()); } fn main() { let mut tmp:Vec<String> = Vec::new(); tmp.push("A String".to_string()); println!("original = {:?}", tmp); mutable_borrow_vec(&mut tmp); println!("modified = {:?}", tmp); } |
This outputs
1 2 | original = ["A String"] modified = ["A String", "Another string"] |
Rust Shared Borrowing
Also using sample codes, Shared Borrowing in Rust means the owner passes a copy of the variable’s value to a function. Therefore, any changes to the function parameter within the function does not change the original variable. The function definition must specify the parameter with & prefixed to the type. For instance, line 1 has this parameter definition – v: &i32. However, codes that call the function must only provide a variable name.
Example 3 – Share Integer Value
1 2 3 4 5 6 7 8 9 10 11 12 | fn shared_borrow(v:&i32) { let v = 600; println!("v={}", v); } fn main() { let mut tmp= 1; println!("original = {:?}", tmp); shared_borrow(&tmp); println!("modified = {:?}", tmp); } |
This outputs
1 2 3 | original = 1 v=600 modified = 1 |
Understanding Ownership
The concept of ownership and how it works is central to these examples for Shared and Mutable borrowing in Rust. For more information, please see Understanding Ownership.