It's all for your own good

These compiler rules are there to help you as a developer. They prevent the sorts of issues commonly found in other languages, the biggest being writing to a variable after it is destroyed or doing something stupid, such as trying to mutate a vector inside of a loop iterating through that vector:

fn main()  
{ 
    let mut myvec = vec![5i32, 10i32, 15i32, 20i32, 25i32, 30i32]; 
     
    for i in &myvec 
    { 
        println!("i = {}", i); 
        myvec.push(35i32);  
    } 
} 
The source for this section is in the 08/invaliditerator folder in the supporting code bundle for this book, with additional discussion in Chapter 5, Memory Management.

This is obviously never going to work. If you think about it, we have a loop that takes myvec as the argument and then, within the loop, we will add to the vector, so the loop never knows about one of the guarantees, as that guarantee is not there: the iterator count. It won't build as well because we are breaking the second borrowing rule.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset