How to fix Rust E0507 cannot move out of index

Fix Rust E0507 by borrowing with & or cloning instead of moving out of a collection.

Fix E0507 by borrowing the element instead of moving it out of the collection. Use & to create a reference or .clone() to copy the value if the type implements Clone.

let vec = vec![String::from("hello"), String::from("world")];
let first = &vec[0]; // Borrow instead of move
println!("{first}");

If you need ownership, clone the value:

let vec = vec![String::from("hello"), String::from("world")];
let first = vec[0].clone(); // Clone to take ownership
println!("{first}");

For mutable access, use &mut:

let mut vec = vec![String::from("hello"), String::from("world")];
let first = &mut vec[0]; // Mutable borrow
first.push_str("!");

If you need to remove the element from the collection, use .remove() or .pop() instead of indexing:

let mut vec = vec![String::from("hello"), String::from("world")];
let first = vec.remove(0); // Remove and take ownership
println!("{first}");