.pop() from immutable vector

Hello :slight_smile:
I'm reading this book
and I don' get something.

fn main() {
    let weather_vec = vec![
        vec!["Berlin", "cloudy", "5", "-7", "78"],
        vec!["Athens", "sunny", "not humid", "20", "10", "50"],
    ];
    for mut city in weather_vec {
        println!("For the city of {}:", city[0]); // In our data, every first item is the city name
        while let Some(information) = city.pop() {
            // This means: keep going until you can't pop anymore
            // When the vector reaches 0 items, it will return None
            // and it will stop.
            if let Ok(number) = information.parse::<i32>() {
                // Try to parse the variable we called information
                // This returns a result. If it's Ok(number), it will print it
                println!("The number is: {}", number);
            }  // We don't write anything here because we do nothing if we get an error. Throw them all away
        }
    }
}

Why it is possible to pop items from inner vectors even though they are define as immutable? I also see this
for mut city in weather_vec
but still can't understand why. :slight_smile:

Thank you for your help and as always sorry for my english. :slight_smile:
Best regards.

Inner vectors are not defined as immutable. The weather_vec binding is immutable, but since it is moved into the for loop, this loop can do with its items (i.e. inner vectors) whatever it wants. In this case, it binds them as mutable (that's what for mut city means).

2 Likes

The short story is that the owner decides whether something is mutable, so when ownership is transferred, the new owner can say that it is mutable, even if the old owner didn't.

4 Likes

Thx guys.
I keep forgetting all that move into for loop thing and that after for loop there is not weather_vec because it was moved.
Sorry for another stupid question. :wink:

There really are no stupid questions when it comes to trying to understand borrow checking in rust. It’s such a foreign concept in just about every other language.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.