Vectors compile

I'm just learning about dynamic arrays in rust. According to the documentation, the following code should give an error when compiling, but it doesn't.

my project:

What documentation? Please link to or include a copy of what you're referring to.

Please post code in code blocks:
```
textual code here
```


I can only guess at what documentation you read, but here are some guesses.

Copy vs. move semantics:

let v = vec![1, 2, 3, 4];
// Maybe you read that this should fail due to move semantics
// But it compiles because `i32: Copy`
let i = v[2];

// This version does not compile (`String` is not `Copy`)
let v = vec![String::new()];
let s = v[0];

// But this is ok because it doesn't try to move `v[0]`
let s_ref = &v[0];

Macros can do what they want:

let v = vec![String::new()];
// This compiles... because macros aren't the same as function calls
//
// (`println!(..)` takes a reference of all the things it prints,
//  so it never attempts to move `v[0]`.)
println!("{}", v[0]);

Something about lexical borrowing?

fn example_3() {
    let mut v = vec![1, 2, 3, 4];

    let third = &v[2];
    println!("{}", third);

    // This didn't fail despite `third` borrowing `v`
    v.push(5);
    println!("{:?}", v);
}

This failed before Rust 1.31 (edition 2018) or Rust 1.36 (edition 2015). But since then -- i.e. for 5+ years -- we've had non-lexical borrows. The &v[2] borrow ends immediately after the first println!, because that's the last place where you use third.

Playground with the examples.

1 Like

Your code is different: in the println!, you use _v[2], not third. You can take a new reference to vector's element, it's the previously created references that are invalidated by push.

2 Likes

I see where the problem is. The compiler is clever enough that I have to modify _v before using third, but my original code does so after I print it, and since I don't use third in my code afterwards, it doesn't cause an error even if the reference to third points to a freed location. After I adjust the code, I get the same error.

1 Like

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.