FAQ - Help and questions

How do I fix "cannot move out of index of Vec" (E0507)?

#errors#ownership#vecpublished 3 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail
Last post

Short answer

Indexing a Vec gives you a place inside it, and moving a String out would leave a hole. Borrow the item with &names[0], copy it with names[0].clone(), or take it out with remove or swap_remove if you really want the Vec to lose it. Types that are Copy, such as numbers, can be indexed directly.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

src/main.rsrust
fn main() {
    let names = vec![String::from("Ada"), String::from("Bo")];
    let first = names[0];
    println!("{first} {}", names.len());
}
text
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.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    3 answers from the Ruststudio team: different approaches, each with its own trade-offs

    Sort: Oldest Newest
    #2

    Approach 1: borrow#

    &names[0] is a reference to the string in place. Nothing is copied, and names is unchanged. This is the right choice when you only read.

    src/main.rsrust
    fn main() {
        let names = vec![String::from("Ada"), String::from("Bo")];
        let first = &names[0]; // borrow it...
        let owned = names[1].clone(); // ...or copy it
        println!("{first} {owned} {}", names.len());
    }
    text
    Ada Bo 2
      QuoteReply
      Share
      Hacker NewsRedditLinkedInE-mail
      #3

      Approach 2: clone#

      names[1].clone() makes an independent String. Use it when you need to keep the text after the vector changes or is dropped. It allocates, so avoid it inside hot loops.

        QuoteReply
        Share
        Hacker NewsRedditLinkedInE-mail
        #4

        Approach 3: take it out of the Vec#

        let first = names.remove(0); removes the item and gives it to you (the later items shift down). names.swap_remove(0) is faster but changes the order, and std::mem::take(&mut names[0]) leaves an empty String behind. Use these when the vector should really lose the value.

        Common mistakes#

        • Cloning to get past the error and then wondering why a change to the copy does not show in the original. A clone is a separate value.
        • Using for name in names and then using names afterwards. The loop consumes the vector; loop over &names to keep it.
          QuoteReply
          Share
          Hacker NewsRedditLinkedInE-mail