Is indexing into a vec a borrow or a move?

To give an example:

fn main() {
    let mut vec = vec!["Hello".to_string()];
    let s: &str = &vec[0]; // reference
    println!("{s}");
    vec[0].push_str(" World!"); // not a move
    println!("{vec:?}");
}

(Playground)

Output:

Hello
["Hello World!"]

1 Like

Using [] operator is really just dereferencing a reference to the element. And even assignment depends on the type of the items to be a move assignment or not.

Given a variable x, would you say that let y = *&x is a move in all cases ?

  • x may be a i32 which is Copy, so let y = *&x is a copy.
  • x may be a String, so let y = *&x is effectively a move.
  • x may be a reference so let y = *&x is actually a copy but you wouldn't consider it really as a copy because you are interested in the value behind the reference. It would appear as a borrow.

The only thing you can tell is that v[i] is equivalent to *Index::index(&v, i), it is nothing more than a dereferencing.

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.