Rust errors / Ownership and borrowing
Rust compiler error · checked with rustc 1.99.0
Rust error E0508: cannot move out of type `[NonCopy; 1]`, a non-copy array
What it meansA value was moved out of a non-copy fixed-size array.
What rustc prints
error[E0508]: cannot move out of type `[NonCopy; 1]`, a non-copy array --> main.rs:5:18 | 5 | let _value = array[0]; // error: cannot move out of type `[NonCopy; 1]`, | ^^^^^^^^ | | | 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 --> main.rs:1:1 | 1 | struct NonCopy; | ^^^^^^^^^^^^^^ consider implementing `Clone` for this type ... 5 | let _value = array[0]; // error: cannot move out of type `[NonCopy; 1]`, | -------- you could clone this value help: consider borrowing here | 5 | let _value = &array[0]; // error: cannot move out of type `[NonCopy; 1]`, | +
Real output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.
The compiler team's explanation
A value was moved out of a non-copy fixed-size array.
Erroneous code example:
struct NonCopy;
fn main() {
let array = [NonCopy; 1];
let _value = array[0]; // error: cannot move out of type `[NonCopy; 1]`,
// a non-copy fixed-size array
}
The first element was moved out of the array, but this is not possible because NonCopy does not implement the Copy trait.
Consider borrowing the element instead of moving it:
struct NonCopy;
fn main() {
let array = [NonCopy; 1];
let _value = &array[0]; // Borrowing is allowed, unlike moving.
}
Alternatively, if your type implements Clone and you need to own the value, consider borrowing and then cloning:
#[derive(Clone)]
struct NonCopy;
fn main() {
let array = [NonCopy; 1];
// Now you can clone the array element.
let _value = array[0].clone();
}
If you really want to move the value out, you can use a destructuring array pattern to move it:
struct NonCopy;
fn main() {
let array = [NonCopy; 1];
// Destructuring the array
let [_value] = array;
}From rustc --explain E0508 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.
Related errors
- E0382borrow of moved value
- E0499cannot borrow as mutable more than once at a time
- E0502cannot borrow as mutable because it is also borrowed as immutable
- E0106missing lifetime specifier
- E0506cannot assign to because it is borrowed
- E0507cannot move out of
- E0509cannot move out of type `DropStruct`, which implements the `Drop` trait
- E0521borrowed data escapes outside of closure
Up next
Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →Did this answer your question?