]>
Commit | Line | Data |
---|---|---|
60c5eb7d XL |
1 | A value was moved out of a non-copy fixed-size array. |
2 | ||
3 | Erroneous code example: | |
4 | ||
5 | ```compile_fail,E0508 | |
6 | struct NonCopy; | |
7 | ||
8 | fn main() { | |
9 | let array = [NonCopy; 1]; | |
10 | let _value = array[0]; // error: cannot move out of type `[NonCopy; 1]`, | |
11 | // a non-copy fixed-size array | |
12 | } | |
13 | ``` | |
14 | ||
15 | The first element was moved out of the array, but this is not | |
16 | possible because `NonCopy` does not implement the `Copy` trait. | |
17 | ||
18 | Consider borrowing the element instead of moving it: | |
19 | ||
20 | ``` | |
21 | struct NonCopy; | |
22 | ||
23 | fn main() { | |
24 | let array = [NonCopy; 1]; | |
25 | let _value = &array[0]; // Borrowing is allowed, unlike moving. | |
26 | } | |
27 | ``` | |
28 | ||
29 | Alternatively, if your type implements `Clone` and you need to own the value, | |
30 | consider borrowing and then cloning: | |
31 | ||
32 | ``` | |
33 | #[derive(Clone)] | |
34 | struct NonCopy; | |
35 | ||
36 | fn main() { | |
37 | let array = [NonCopy; 1]; | |
38 | // Now you can clone the array element. | |
39 | let _value = array[0].clone(); | |
40 | } | |
41 | ``` | |
136023e0 XL |
42 | |
43 | If you really want to move the value out, you can use a destructuring array | |
44 | pattern to move it: | |
45 | ||
46 | ``` | |
47 | struct NonCopy; | |
48 | ||
49 | fn main() { | |
50 | let array = [NonCopy; 1]; | |
51 | // Destructuring the array | |
52 | let [_value] = array; | |
53 | } | |
54 | ``` |