Rust

E0508 Cannot Move Out of Array Fix

An array is one value, not a row of separate slots the compiler will let you empty one at a time. Moving a single element out of a fixed-size array would leave the array with a hole - one element gone, the rest in place - and Rust has no state for a partly emptied array, so any index expression that tries to move a non-Copy element out is refused with E0508. This guide separates the eleven shapes that produce it and matches each one to its repair: borrow the element, clone it, swap a replacement into its place, or move the whole array at once and take the elements from the owned value.

Written November 25, 2026 · Tested with Rust 1.99.1 · 30 min read

By the end of this guide
  • The rule underneath: an array has no empty slots
  • How to read the diagnostic
  • The first failure: binding an element directly
  • The second failure: the error index example

Written November 25, 2026

Tested with Rust 1.99.1

What this guide is

Error E0508 is a move that would tear one element out of a fixed-size array. The error codes index describes it as a value moved out of a non-copy fixed-size array, and its example moves the first element of a one-element array of a struct that does not implement Copy. Moving that element out by value would leave the array missing an element while the rest of the array is still there, and an array value has a fixed number of elements for its whole life - there is no partly filled array for the compiler to track. The index expression is therefore only allowed to copy the element out, which needs the element type to be Copy, or to borrow it.

The forms in this guide each reproduce E0508 with a small, complete program, and in each one the element is reached a different way: bound directly by index, held in an array of a plain non-copy struct, indexed by a variable, handed to a function, returned from a function, taken from a nested array, taken from an array stored in a struct field, taken from an array of Vec values, produced by one arm of a match, taken from an array literal with no name at all, and consumed by a method call on the element. The repairs are fewer than the shapes. Either the element is borrowed or cloned so the array stays whole, or a replacement is swapped into the element's place so the array is never left with a hole, or the whole array is moved at once - by destructuring, or by into_iter - so every element leaves together and no hole can form.

Two neighboring results are not E0508 and are worked only in the traps below. Moving an element out of a Vec by index is E0507, because a Vec index goes through the Index trait rather than a built-in array place. Moving an element out of an array field reached through a borrowed struct is also E0507, because that place sits behind a shared reference. Indexing an array through a single shared reference to the array itself is different — that is still E0508, as one of the seven more shapes below shows.

Build every program in this guide with rustc --edition 2021. In the compiler transcripts below, the file names are the bare names shown on the command line.

The rule underneath: an array has no empty slots

An array type [T; N] holds exactly N values of T, and the array expressions section of the Reference describes an array as a value containing each of its elements - the value is the whole set, in order. A move is a transfer of ownership that leaves the source unusable, so moving element 0 out of a live array would need a state the type cannot express: an array of two elements where one of them is absent. Rather than invent that state, the compiler refuses the move at the index expression, for every way of reaching the element - through a variable, a field, a nested index, or a literal.

Copy is the exception that proves the rule. The Copy trait marks types whose values can be duplicated simply by copying bits, and a type with Copy semantics is not moved by an assignment or a binding - it is copied, and the source stays fully usable. Indexing a [i32; 3] therefore works: a[0] copies the integer out and the array is untouched. A String, a Vec, or a plain struct without Copy has move semantics instead, and for those element types the same index expression is E0508.

That split is also why the fixes fall into three groups. Borrowing and cloning never disturb the array: &a[0] reads the element in place, and a[0].clone() builds a new owned value from a borrow. std::mem::take and std::mem::replace move the element out but put a replacement value in its slot in the same step, so the array is whole at every point the program can observe. And moving the whole array - destructuring it into its elements, or consuming it with into_iter - is allowed because the array itself is gone afterward; there is no remainder to leave a hole in.

How to read the diagnostic

Every failure in the eleven families prints the same header, span and note shape; the helps vary with the shape — some offer borrow and clone, some only clone, and the non-copy struct family adds a note about Clone instead. The first family's, in full:

Terminal
$ rustc --edition 2021 fail_direct.rs -o fail_direct
error[E0508]: cannot move out of type `[String; 2]`, a non-copy array
 --> fail_direct.rs:3:13
  |
3 |     let s = a[0];
  |             ^^^^
  |             |
  |             cannot move out of here
  |             move occurs because `a[_]` has type `String`, which does not implement the `Copy` trait
  |
help: consider borrowing here
  |
3 |     let s = &a[0];
  |             +
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let s = a[0].clone();
  |                 ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0508`.

Read it in order. The header names the array type and states the whole problem: the array is a non-copy array, meaning its element type does not implement Copy. The span underlines the index expression and labels it "cannot move out of here", and the note under the span names the element type and the missing trait - "move occurs because a[_] has type String, which does not implement the Copy trait". The two helps then offer the two repairs that keep the array whole: borrow the element, by adding &, or clone it, by adding .clone(). When neither help fits - because the program truly needs to own the element - the remaining repairs are the swap-in-place and whole-array moves covered in the families below.

That shape is also the fastest way to separate E0508 from its neighbors before touching code. If the header says "cannot move out of type" followed by an array type in brackets, the array itself is the obstacle and this guide applies. If it says "cannot move out of index of" a Vec, or "cannot move out of" a place "behind a shared reference", the code is E0507 - a different obstacle, worked in the traps.

The first failure: binding an element directly

The simplest shape - one element of a String array bound to a new variable:

Rust
fn main() {
    let a = [String::from("one"), String::from("two")];
    let s = a[0];
    println!("{}", s);
}
Terminal
$ rustc --edition 2021 fail_direct.rs -o fail_direct
error[E0508]: cannot move out of type `[String; 2]`, a non-copy array
 --> fail_direct.rs:3:13
  |
3 |     let s = a[0];
  |             ^^^^
  |             |
  |             cannot move out of here
  |             move occurs because `a[_]` has type `String`, which does not implement the `Copy` trait
  |
help: consider borrowing here
  |
3 |     let s = &a[0];
  |             +
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let s = a[0].clone();
  |                 ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0508`.

The binding asks for the element by value, and a String cannot be copied out, so the move is refused. The fix borrows the element instead, which is the diagnostic's first help:

Rust
fn main() {
    let a = [String::from("one"), String::from("two")];
    let s = &a[0];
    println!("{} {}", s, a[1]);
}
Terminal
$ rustc --edition 2021 fix_direct.rs -o fix_direct
$ ./fix_direct
one two

The output is one two: the borrow reads the first element, and the second element is still there to print because the array never lost anything. Borrowing is the right repair whenever the code only needs to read the element, which is most of the time this error appears.

The second failure: the error index example

The example from the error codes index - a one-element array of a struct with no Copy implementation:

Rust
struct NonCopy;
fn main() {
    let array = [NonCopy; 1];
    let _value = array[0];
}
Terminal
$ rustc --edition 2021 fail_noncopy.rs -o fail_noncopy
error[E0508]: cannot move out of type `[NonCopy; 1]`, a non-copy array
 --> fail_noncopy.rs:4:18
  |
4 |     let _value = array[0];
  |                  ^^^^^^^^
  |                  |
  |                  cannot move out of here
  |                  move occurs because `array[_]` has type `NonCopy`, which does not implement the `Copy` trait
  |
note: if `NonCopy` implemented `Clone`, you could clone the value
 --> fail_noncopy.rs:1:1
  |
1 | struct NonCopy;
  | ^^^^^^^^^^^^^^ consider implementing `Clone` for this type
...
4 |     let _value = array[0];
  |                  -------- you could clone this value
help: consider borrowing here
  |
4 |     let _value = &array[0];
  |                  +

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0508`.

There is nothing special about String here: any element type without Copy fails the same way, and this diagnostic adds a note pointing out that the struct does not implement Clone either, so the clone help is not offered. The index page's third route is destructuring - move the whole array into a pattern, so the element leaves as part of the array's own move:

Rust
struct NonCopy;
fn main() {
    let array = [NonCopy; 1];
    let [_value] = array;
    println!("moved");
}
Terminal
$ rustc --edition 2021 fix_noncopy.rs -o fix_noncopy
$ ./fix_noncopy
moved

The output is moved. The pattern let [_value] = array; takes ownership of the array and binds its one element in the same step; nothing remains behind to have a hole in it. Destructuring fits when the array is finished with and every element is wanted at once.

The third failure: an index held in a variable

The same binding, with the position computed in a variable instead of written as a literal:

Rust
fn main() {
    let a = [String::from("one"), String::from("two")];
    let i = 1;
    let s = a[i];
    println!("{}", s);
}
Terminal
$ rustc --edition 2021 fail_var_index.rs -o fail_var_index
error[E0508]: cannot move out of type `[String; 2]`, a non-copy array
 --> fail_var_index.rs:4:13
  |
4 |     let s = a[i];
  |             ^^^^
  |             |
  |             cannot move out of here
  |             move occurs because `a[_]` has type `String`, which does not implement the `Copy` trait
  |
help: consider borrowing here
  |
4 |     let s = &a[i];
  |             +
help: consider cloning the value if the performance cost is acceptable
  |
4 |     let s = a[i].clone();
  |                 ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0508`.

A variable index changes nothing: the compiler cannot know which element i names at compile time, and it does not matter - every element of the array is equally unmovable, so the error is the same whatever value i holds. The fix clones the element at the computed index:

Rust
fn main() {
    let a = [String::from("one"), String::from("two")];
    let i = 1;
    let s = a[i].clone();
    println!("{} {}", s, a[0]);
}
Terminal
$ rustc --edition 2021 fix_var_index.rs -o fix_var_index
$ ./fix_var_index
two one

The output is two one: the clone is the second element, and the first element still prints afterward because the original array is intact. Cloning costs a new allocation for a String; it is the honest price when the program needs an owned value and the array must keep its element.

The fourth failure: an element as a function argument

An element passed to a function that takes it by value:

Rust
fn take(s: String) {
    println!("{}", s);
}
fn main() {
    let a = [String::from("one"), String::from("two")];
    take(a[0]);
}
Terminal
$ rustc --edition 2021 fail_fn_arg.rs -o fail_fn_arg
error[E0508]: cannot move out of type `[String; 2]`, a non-copy array
 --> fail_fn_arg.rs:6:10
  |
6 |     take(a[0]);
  |          ^^^^
  |          |
  |          cannot move out of here
  |          move occurs because `a[_]` has type `String`, which does not implement the `Copy` trait
  |
help: consider cloning the value if the performance cost is acceptable
  |
6 |     take(a[0].clone());
  |              ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0508`.

Passing an argument by value is a move, so the call site is where the error lands - the function itself is fine. When the function only reads the value, the repair is on both sides of the call: the function takes a reference, and the call passes one:

Rust
fn take(s: &String) {
    println!("{}", s);
}
fn main() {
    let a = [String::from("one"), String::from("two")];
    take(&a[0]);
}
Terminal
$ rustc --edition 2021 fix_fn_arg.rs -o fix_fn_arg
$ ./fix_fn_arg
one

The output is one. Changing the parameter to &String makes the call a borrow, and the element stays in the array. Where the function genuinely needs to own its argument, the call-site version of the same repair is take(a[0].clone()) - the function receives an owned clone and the array keeps the original.

The fifth failure: returning an element

A function that owns an array parameter and tries to return its first element:

Rust
fn get(a: [String; 2]) -> String {
    a[0]
}
fn main() {
    let a = [String::from("one"), String::from("two")];
    println!("{}", get(a));
}
Terminal
$ rustc --edition 2021 fail_return.rs -o fail_return
error[E0508]: cannot move out of type `[String; 2]`, a non-copy array
 --> fail_return.rs:2:5
  |
2 |     a[0]
  |     ^^^^
  |     |
  |     cannot move out of here
  |     move occurs because `a[_]` has type `String`, which does not implement the `Copy` trait
  |
help: consider cloning the value if the performance cost is acceptable
  |
2 |     a[0].clone()
  |         ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0508`.

Owning the array does not help: the function returns one element and would drop the rest, and the drop still needs the array whole at the point of the move. The fix consumes the array with into_iter, which moves every element out of the owned array in order, and takes the first:

Rust
fn get(a: [String; 2]) -> String {
    a.into_iter().next().unwrap()
}
fn main() {
    let a = [String::from("one"), String::from("two")];
    println!("{}", get(a));
}
Terminal
$ rustc --edition 2021 fix_return.rs -o fix_return
$ ./fix_return
one

The output is one. into_iter on an array yields its elements by value precisely because it consumes the array itself - the whole-array move that leaves no hole. The remaining elements are dropped with the iterator, which is what returning only the first element always implied.

The sixth failure: an element of a nested array

An element taken from an array inside another array:

Rust
fn main() {
    let a = [[String::from("one"), String::from("two")], [String::from("three"), String::from("four")]];
    let s = a[0][0];
    println!("{}", s);
}
Terminal
$ rustc --edition 2021 fail_nested.rs -o fail_nested
error[E0508]: cannot move out of type `[[String; 2]; 2]`, a non-copy array
 --> fail_nested.rs:3:13
  |
3 |     let s = a[0][0];
  |             ^^^^^^^
  |             |
  |             cannot move out of here
  |             move occurs because `a[_][_]` has type `String`, which does not implement the `Copy` trait
  |
help: consider borrowing here
  |
3 |     let s = &a[0][0];
  |             +
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let s = a[0][0].clone();
  |                    ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0508`.

The header names the outer type, [[String; 2]; 2], because the first index is where the move starts: a[0] would have to move the inner array out of the outer one before the second index could take the String out of that. The fix borrows through both indices:

Rust
fn main() {
    let a = [[String::from("one"), String::from("two")], [String::from("three"), String::from("four")]];
    let s = &a[0][0];
    println!("{} {}", s, a[1][1]);
}
Terminal
$ rustc --edition 2021 fix_nested.rs -o fix_nested
$ ./fix_nested
one four

The output is one four: the borrowed element prints, and the far corner of the array is still reachable, because a chain of indices borrows as readily as it refuses to move. Each index in the chain is a place inside the value before it, and a move at any step of the chain is a move out of that value.

The seventh failure: an array in a struct field

An element taken from an array stored in a struct's field:

Rust
struct Holder {
    items: [String; 2],
}
fn main() {
    let h = Holder { items: [String::from("one"), String::from("two")] };
    let s = h.items[0];
    println!("{}", s);
}
Terminal
$ rustc --edition 2021 fail_struct_field.rs -o fail_struct_field
error[E0508]: cannot move out of type `[String; 2]`, a non-copy array
 --> fail_struct_field.rs:6:13
  |
6 |     let s = h.items[0];
  |             ^^^^^^^^^^
  |             |
  |             cannot move out of here
  |             move occurs because `h.items[_]` has type `String`, which does not implement the `Copy` trait
  |
help: consider borrowing here
  |
6 |     let s = &h.items[0];
  |             +
help: consider cloning the value if the performance cost is acceptable
  |
6 |     let s = h.items[0].clone();
  |                       ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0508`.

The field access changes nothing about the index: h.items is a place inside h, and h.items[0] is a place inside that, and a move out of the innermost place would leave both the array and the struct incomplete. The fix uses std::mem::take, which moves the element out and leaves the element type's default value in its place - for String, an empty string:

Rust
struct Holder {
    items: [String; 2],
}
fn main() {
    let mut h = Holder { items: [String::from("one"), String::from("two")] };
    let s = std::mem::take(&mut h.items[0]);
    println!("{} {}", s, h.items[1]);
}
Terminal
$ rustc --edition 2021 fix_struct_field.rs -o fix_struct_field
$ ./fix_struct_field
one two

The output is one two: the taken element prints, and the second element is undisturbed. take needs the element type to implement Default and a mutable path to the array, which is why the struct binding is mut here. Where there is no sensible default, std::mem::replace with an explicit replacement value does the same job, as the alternatives below show.

The eighth failure: an element of an array of Vec values

An element taken from an array whose elements are Vec values:

Rust
fn main() {
    let a = [vec![1, 2], vec![3]];
    let v = a[0];
    println!("{:?}", v);
}
Terminal
$ rustc --edition 2021 fail_vec_array.rs -o fail_vec_array
error[E0508]: cannot move out of type `[Vec<i32>; 2]`, a non-copy array
 --> fail_vec_array.rs:3:13
  |
3 |     let v = a[0];
  |             ^^^^
  |             |
  |             cannot move out of here
  |             move occurs because `a[_]` has type `Vec<i32>`, which does not implement the `Copy` trait
  |
help: consider borrowing here
  |
3 |     let v = &a[0];
  |             +
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let v = a[0].clone();
  |                 ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0508`.

The element type is Vec<i32> - itself a growable buffer with move semantics - and the header names the array type [Vec<i32>; 2]. The fix is the same swap as the struct field family, since a Vec also has a default: an empty vector:

Rust
fn main() {
    let mut a = [vec![1, 2], vec![3]];
    let v = std::mem::take(&mut a[0]);
    println!("{:?} {:?}", v, a[1]);
}
Terminal
$ rustc --edition 2021 fix_vec_array.rs -o fix_vec_array
$ ./fix_vec_array
[1, 2] [3]

The output is [1, 2] [3]: the taken vector prints in full, and the second vector is untouched. The array still holds two vectors afterward - the first is empty, not absent - which is exactly the distinction the error is enforcing.

The ninth failure: an element in a match arm

An element produced by one arm of a match:

Rust
fn main() {
    let a = [String::from("one"), String::from("two")];
    let s = match true {
        true => a[0],
        false => String::from("other"),
    };
    println!("{}", s);
}
Terminal
$ rustc --edition 2021 fail_match.rs -o fail_match
error[E0508]: cannot move out of type `[String; 2]`, a non-copy array
 --> fail_match.rs:4:17
  |
4 |         true => a[0],
  |                 ^^^^
  |                 |
  |                 cannot move out of here
  |                 move occurs because `a[_]` has type `String`, which does not implement the `Copy` trait
  |
help: consider borrowing here
  |
4 |         true => &a[0],
  |                 +
help: consider cloning the value if the performance cost is acceptable
  |
4 |         true => a[0].clone(),
  |                     ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0508`.

A match arm is a value-producing expression like any other, and an arm that evaluates to a[0] is a move out of the array. The fix borrows in both arms, so the match yields a reference whichever arm is taken:

Rust
fn main() {
    let a = [String::from("one"), String::from("two")];
    let s: &String = match true {
        true => &a[0],
        false => &a[1],
    };
    println!("{}", s);
}
Terminal
$ rustc --edition 2021 fix_match.rs -o fix_match
$ ./fix_match
one

The output is one, from the arm that ran. Both arms must agree on the type they produce, which is why the fallback arm borrows the second element rather than building a new String - a &String and a String cannot be the two results of one expression.

The tenth failure: an element of an array literal

An element taken from an array literal that was never bound to a name:

Rust
fn main() {
    let s = [String::from("one"), String::from("two")][0];
    println!("{}", s);
}
Terminal
$ rustc --edition 2021 fail_literal.rs -o fail_literal
error[E0508]: cannot move out of type `[String; 2]`, a non-copy array
 --> fail_literal.rs:2:13
  |
2 |     let s = [String::from("one"), String::from("two")][0];
  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |             |
  |             cannot move out of here
  |             move occurs because value has type `String`, which does not implement the `Copy` trait
  |
help: consider borrowing here
  |
2 |     let s = &[String::from("one"), String::from("two")][0];
  |             +
help: consider cloning the value if the performance cost is acceptable
  |
2 |     let s = [String::from("one"), String::from("two")][0].clone();
  |                                                          ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0508`.

There is no variable to blame - the literal itself is the array value, and indexing it by value is the same move. The fix consumes the literal with into_iter, as in the return family:

Rust
fn main() {
    let s = [String::from("one"), String::from("two")].into_iter().next().unwrap();
    println!("{}", s);
}
Terminal
$ rustc --edition 2021 fix_literal.rs -o fix_literal
$ ./fix_literal
one

The output is one. A literal is a value like any other: it can be consumed whole, borrowed from once bound, or cloned from - it just cannot be partly emptied, because even a temporary array has no state for a missing element.

The eleventh failure: an element consumed by a method

An element passed to a method that consumes it - here into_bytes, which takes the String by value:

Rust
fn main() {
    let a = [String::from("one"), String::from("two")];
    let bytes = a[0].into_bytes();
    println!("{:?}", bytes);
}
Terminal
$ rustc --edition 2021 fail_method_consume.rs -o fail_method_consume
error[E0508]: cannot move out of type `[String; 2]`, a non-copy array
 --> fail_method_consume.rs:3:17
  |
3 |     let bytes = a[0].into_bytes();
  |                 ^^^^
  |                 |
  |                 cannot move out of here
  |                 move occurs because `a[_]` has type `String`, which does not implement the `Copy` trait
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let bytes = a[0].clone().into_bytes();
  |                     ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0508`.

A method call that takes self by value is a move of its receiver, and the receiver here is the place a[0], so the call is refused at the index. The fix clones the element and consumes the clone:

Rust
fn main() {
    let a = [String::from("one"), String::from("two")];
    let bytes = a[0].clone().into_bytes();
    println!("{:?} {}", bytes, a[0]);
}
Terminal
$ rustc --edition 2021 fix_method_consume.rs -o fix_method_consume
$ ./fix_method_consume
[111, 110, 101] one

The output is [111, 110, 101] one: the byte values of one, and the original element still in the array to print afterward. Any consuming method - into_bytes, into_boxed_str, a consuming iterator adapter - raises the same error on an array element, and the choice is always the same three: borrow if a borrowing method exists, clone if the array must survive, or take the element out with a swap if it must be owned outright.

Seven more shapes that fail the same way

The same header — naming the array type the move starts from, or, for the slice shape below, the slice type — for seven more programs. Each fails with exactly one E0508 and no other error, and each is repaired by the same three groups of fixes - borrow or clone, swap a replacement in, or move the whole array:

An array parameter of a function, indexed inside the body - owning the parameter does not make its elements movable:

Rust
fn first(a: [String; 2]) {
    let s = a[1];
    println!("{}", s);
}
fn main() {
    first([String::from("one"), String::from("two")]);
}

A field of a tuple holding an array:

Rust
fn main() {
    let t = ([String::from("one"), String::from("two")], 7);
    let s = t.0[0];
    println!("{}", s);
}

An array behind a Box - the box owns the array, and the index still moves out of the array itself:

Rust
fn main() {
    let a = Box::new([String::from("one"), String::from("two")]);
    let s = a[0];
    println!("{}", s);
}

An index through a reference to the array - the header still names the array type, because the place the index reaches is the array's element:

Rust
fn main() {
    let a = [String::from("one"), String::from("two")];
    let r = &a;
    let s = r[0];
    println!("{}", s);
}

An assignment statement instead of a binding - assigning a[1] into an existing variable is the same move:

Rust
fn main() {
    let a = [String::from("one"), String::from("two")];
    let mut s = String::new();
    s = a[1];
    println!("{}", s);
}

An index into a slice taken from the array - the header calls the type [String] "a non-copy slice", the same refusal one step removed from the array:

Rust
fn main() {
    let a = [String::from("one"), String::from("two")];
    let s: &[String] = &a;
    let x = s[0];
    println!("{}", x);
}

An array built with the repeat form, [value; 1] - the construction form makes no difference to the move:

Rust
struct NonCopy {
    v: i32,
}
fn main() {
    let array = [NonCopy { v: 1 }; 1];
    let _value = array[0];
}

When the element really has to move

Two repairs cover the cases the families above route around: the program needs the element itself, owned, and the array must go on existing without it.

Swap in a replacement with std::mem::replace. Where take leaves the type's default, replace leaves a value the program chooses:

Rust
fn main() {
    let mut a = [String::from("one"), String::from("two")];
    let s = std::mem::replace(&mut a[0], String::from("new"));
    println!("{} {}", s, a[0]);
}
Terminal
$ rustc --edition 2021 alt_mem_replace.rs -o alt_mem_replace
$ ./alt_mem_replace
one new

The output is one new: the original first element is owned by s, and the array's first slot holds the replacement. The array keeps its length and stays usable - it has simply traded one element for another, which is the only way an element can leave a live array.

Make the element type Copy. When the element is a small plain-data value, the honest fix is often at the type: derive Copy (with Clone, which Copy requires), and the index expression copies instead of moving:

Rust
#[derive(Copy, Clone)]
struct Point {
    v: i32,
}
fn main() {
    let a = [Point { v: 1 }, Point { v: 2 }];
    let p = a[0];
    println!("{} {}", p.v, a[1].v);
}
Terminal
$ rustc --edition 2021 alt_copy_type.rs -o alt_copy_type
$ ./alt_copy_type
1 2

The output is 1 2: a[0] copies the Point out, and a[1] is still there. This is not a workaround for heap-owning types - a type that owns a buffer, like String or Vec, cannot be Copy, because copying its bits would duplicate the pointer and double-own the buffer. It is the right answer exactly when the value is plain data with nothing behind a pointer.

The neighbors that compile

These programs move or read array elements with no error, each because it stays inside what an array allows.

A Copy element array: indexing copies the element out, and the array is untouched:

Rust
fn main() {
    let a = [1, 2, 3];
    let x = a[0];
    println!("{} {}", x, a[1]);
}
Terminal
$ rustc --edition 2021 ok_copy_array.rs -o ok_copy_array
$ ./ok_copy_array
1 2

The output is 1 2. This is the shape E0508 is the failure of: same syntax, same binding, and the only difference is the element type's trait.

Iterating the array by value: the loop consumes the whole array, so each element moves out of an array that no longer exists afterward:

Rust
fn main() {
    let a = [String::from("one"), String::from("two")];
    for s in a {
        println!("{}", s);
    }
}
Terminal
$ rustc --edition 2021 ok_iter_value.rs -o ok_iter_value
$ ./ok_iter_value
one
two

The output is one then two. A for loop over an array takes the array by value - the whole-array move again, one element at a time, with nothing left behind.

Borrowing a range of the array: a range index produces a slice, and borrowing the slice reads the elements in place:

Rust
fn main() {
    let a = [String::from("one"), String::from("two")];
    let s = &a[0..1];
    println!("{}", s[0]);
}
Terminal
$ rustc --edition 2021 ok_range_slice.rs -o ok_range_slice
$ ./ok_range_slice
one

The output is one. A range never names a single element to move; it names a view over a run of elements, and views are borrows.

An array of references: the elements are &String values, and shared references are Copy, so indexing copies the reference out:

Rust
fn main() {
    let x = String::from("one");
    let y = String::from("two");
    let refs = [&x, &y];
    let r = refs[0];
    println!("{}", r);
}
Terminal
$ rustc --edition 2021 ok_ref_elems.rs -o ok_ref_elems
$ ./ok_ref_elems
one

The output is one. What is copied is the reference, not the string - the array's element type decides the error, and a reference element type is a copyable one.

The fixes in reach order

  • The code only reads the element: borrow it - &a[i] - or call a borrowing method on it. This is the diagnostic's first help and the most common repair.
  • The code needs an owned value and the array must keep its element: clone it - a[i].clone(). This is the diagnostic's second help; the cost is a fresh copy of the element.
  • The code needs the element itself and the array must stay whole: swap a replacement in with std::mem::take (leaves the default value) or std::mem::replace (leaves a chosen value). Both need a mutable path to the element.
  • The array is finished with: move it whole - destructure it into its elements, or consume it with into_iter and take the elements from the iterator.
  • The element is small plain data: make its type Copy and the index copies. Never available for types that own a buffer.
  • The header is not E0508: "cannot move out of index of" a Vec and "behind a shared reference" are E0507 - both in the traps, both fixed by borrowing or cloning. A swap also works where a mutable place is available — std::mem::take(&mut v[0]) on a mutable Vec, for example — but not for a place behind a shared reference, where no mutable place exists.

Traps

  • Moving an element out of a Vec by index is E0507, not E0508. A Vec is not an array: its index expression goes through the Index trait and produces a place behind the vector's buffer, and moving out of it gets its own code:
Rust
fn main() {
    let v = vec![String::from("one"), String::from("two")];
    let s = v[0];
    println!("{}", s);
}
Terminal
$ rustc --edition 2021 trap_vec_index.rs -o trap_vec_index
error[E0507]: cannot move out of index of `Vec<String>`
 --> trap_vec_index.rs:3:13
  |
3 |     let s = v[0];
  |             ^^^^ move occurs because value has type `String`, which does not implement the `Copy` trait
  |
help: consider borrowing here
  |
3 |     let s = &v[0];
  |             +
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let s = v[0].clone();
  |                 ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0507`.
Trap
The helps look the same - borrow or clone - because the repairs overlap, and a take-style swap works on a mutable vector too — std::mem::take(&mut v[0]) leaves the type's default value in the slot — alongside the vector's own methods, such as removing or popping the element, which change its length instead of leaving a replacement. - Moving an element out of an array field reached through a borrowed struct is also E0507. When the array is reached as a field of a value the code only borrows, the obstacle is not the array but the borrow: nothing can be moved out of borrowed content, whatever the type. (Indexing an array through a shared reference to the array itself is still E0508 — see the seven more shapes above.)
Rust
struct Holder {
    items: [String; 2],
}
fn get(h: &Holder) -> String {
    h.items[0]
}
fn main() {
    let h = Holder { items: [String::from("one"), String::from("two")] };
    println!("{}", get(&h));
}
Terminal
$ rustc --edition 2021 trap_borrowed_field.rs -o trap_borrowed_field
error[E0507]: cannot move out of `h.items[_]` which is behind a shared reference
 --> trap_borrowed_field.rs:5:5
  |
5 |     h.items[0]
  |     ^^^^^^^^^^ move occurs because `h.items[_]` has type `String`, which does not implement the `Copy` trait
  |
help: consider cloning the value if the performance cost is acceptable
  |
5 |     h.items[0].clone()
  |               ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0507`.

The header says the place is "behind a shared reference" and offers only the clone help - borrowing the element further is possible, but no swap or whole-array move exists, because the function does not own the array at all. Getting ownership of the array, cloning the element, or changing the function to return a borrow of the element are the only doors out.

Checklist

  • The header checked: an array type in brackets after "cannot move out of type" is E0508; a Vec index or a place behind a shared reference is E0507.
  • The element's use classified before the repair: read-only (borrow), owned copy acceptable (clone), the element itself required (swap or whole-array move), or plain data (make the type Copy).
  • Every index expression in the program checked, not just the one in the first diagnostic - nested indices, field paths, match arms, and method receivers all reach elements the same way.
  • For a swap fix, a mutable path to the array confirmed, and the replacement - default or chosen - one the program can live with in the slot afterward.
  • For a whole-array move, the rest of the array accounted for: destructuring binds or drops every element, and into_iter drops whatever the program does not take.
  • No Copy derive added to a type that owns a buffer - the compiler refuses it, and the refusal is correct.
  • The fixed program run, and its output checked against what the program was meant to print.

Sources

  • Rust, Error codes index: E0508 — for the definition of the error as a value moved out of a non-copy fixed-size array, for its example of moving an element of a one-element array of a non-copy struct, and for its three repairs: borrowing the element, cloning it, and destructuring the array to move the element out.
  • The Rust Reference, Array expressions — for arrays as values containing each of their elements in order, and for the two construction forms, the element list and the repeat form.
  • The Rust Standard Library, Copy — for Copy as the trait for types whose values can be duplicated simply by copying bits, for copy semantics as the alternative to move semantics, and for Clone as a required supertrait of Copy.

Keep Exploring