Answer#
let first = names[0]; tries to move the String out of the vector. After that, the vector would contain an item that no longer exists, and freeing it later would be a double free, so Rust refuses. The same error appears when you take a field out of a struct behind a reference, or call a method that takes self on something you only borrowed.
fn main() {
let names = vec![String::from("Ada"), String::from("Bo")];
let first = names[0];
println!("{first} {}", names.len());
}error[E0507]: cannot move out of index of `Vec<String>`
--> src/main.rs:3:17
|
3 | let first = names[0];
| ^^^^^^^^ move occurs because value has type `String`, which does not implement the `Copy` trait
|
help: consider borrowing here
|
3 | let first = &names[0];
| +
help: consider cloning the value if the performance cost is acceptable
|
3 | let first = names[0].clone();
| ++++++++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0507`.The answers below are the three valid fixes.