2
votes

Below is a code snippet (playground) that I tried to run:

fn main() {
    let a = vec!["hello".to_string(), "world".to_string()];
    let b = vec![10, 20, 30];

    let c = a[0];
    let d = b[0];

    println!("{:?}", c);
    println!("{:?}", d);
}

The error says that "values can't be moved out of borrowed content":

error[E0507]: cannot move out of borrowed content
 --> src/main.rs:5:13
  |
5 |     let c = a[0];
  |             ^^^^
  |             |
  |             cannot move out of borrowed content
  |             help: consider borrowing here: `&a[0]`

But I don't see any explicit borrowing being done. Where exactly is the borrowing done? And what is borrowed? And what is the borrowed content mentioned in the error?

This doesn't happen with primitive types like floats, chars etc. Maybe because values are copied rather than being moved, which is possible only in case of primitives (data structures whose values are completely stored in stack rather than in heap).

1
Hi, please include a minimal reproducible example in the text of the question itself, so people can read the question without clicking an extra link, and so that the question will still be useful to future readers if the link breaks. - IMSoP
I will keep this in mind next time I ask a question thank you - Satoshi Gekkouga

1 Answers

4
votes

Assignments move values in this case. Basically, let stuff = a[0] attempts to move the value at the 0th index of vector a, which would leave this index somehow undefined, which isn't allowed in Rust. The expression a[0] borrows the value at index zero, because it's syntactic sugar for *a.index(0), where index returns the borrowed value.

This is discussed in the Rust book and in Rust by example in more detail.