capypad
0 day streak
rust / beginner
Snippet

Mutable References in Functions

Primitive arguments are passed by value (copied). The function receives a copy, so the original remains unchanged. To modify the original, pass a mutable reference: &mut num, or return the new value.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
fn increment(mut value: i32) {
value += 1;
}
 
fn main() {
let mut num = 5;
increment(num);
println!("{}", num);
}
Breakdown
1
fn increment(mut value: i32)
Parameters receive a copy of the value. mut allows local modification inside the function.
2
num stays 5
The original num in main is unaffected because a copy was passed.