I have the following code:
fn main() {
let mut vec1 = vec![1, 2, 3];
vec1.push(4);
println!("{:?}", vec1);
let vec2 = vec![1, 2, 3];
vec2.push(4);
println!("{:?}", vec2);
}
I've created two vectors, one is mutable and another one is immutable. When I try to compile the code, the compiler complains:
error[E0596]: cannot borrow `vec2` as mutable, as it is not declared as mutable
--> src/main.rs:7:5
|
6 | let vec2 = vec![1, 2, 3];
| ---- help: consider changing this to be mutable: `mut vec2`
7 | vec2.push(4);
| ^^^^ cannot borrow as mutable
This is clear, why error occurs, because vec2
is immutable.
Let's take a look at vec!
macro implementation:
macro_rules! vec {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}
The temp_vec
variable is defined as mutable. When I create a vector like
let vec2 = vec![1, 2, 3];
then why vec2
does not become mutable too? I interpret as:
let vec2 = temp_vec
so it is variable shadowing.