0

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.

softshipper
  • 32,463
  • 51
  • 192
  • 400
  • Not so. What does it mean `This shows that mutability is not a property of the type of a value, but rather of its binding`? – softshipper Jan 16 '20 at 16:50
  • 1
    In your case it means the binding/variable vec2 is immutable (because you've not marked it as mutable). Inside the macro the binding/variable temp_vec is mutable. Both are still just type "Vec", there is no type "mutable Vec" or "immutable Vec". – Jussi Kukkonen Jan 16 '20 at 16:56

0 Answers0