Closed dataCobra closed 1 month ago
Hello,
Adding mut
in front of a function parameter makes the parameter (or more accurately variable) itself mutable within the function body, exactly like in a variable declaration.
So you can think of:
fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {
vec.push(88);
vec
}
As:
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
vec.push(88);
vec
}
Without the ability to add mut
to function parameters you would have to manually shadow them if you wanted to modify them, using the let mut x = x
pattern.
Thank you for the great explanation. :)
Just adding something to the great answer by @ProdOrDev
How does the function make the given vec0 borrowed variable mutable?
vec0
is not borrowed here (not &Vec<i32>
or &[i32]
). It is moved (Vec<i32>
). So the function owns the vector. If you own a value, you can also mutate it. If it is not declared as mutable, you can shadow it as @ProdOrDev explained.
Hello,
I just completed
move_semantics3.rs
and was wondering how does themut
in front of a parameter work.The variable
vec0
is not mutable as a variable and also vectors don't have copy implemented.How does the function make the given
vec0
borrowed variable mutable?I couldn't find an explanation and hope you can enlighten me.
Best regards dataCobra