如何实现 Rust 的 Copy trait?

我正试图在 Rust 中初始化一个结构数组:

enum Direction {
North,
East,
South,
West,
}


struct RoadPoint {
direction: Direction,
index: i32,
}


// Initialise the array, but failed.
let data = [RoadPoint { direction: Direction::East, index: 1 }; 4];

当我尝试编译时,编译器抱怨 Copy trait 没有实现:

error[E0277]: the trait bound `main::RoadPoint: std::marker::Copy` is not satisfied
--> src/main.rs:15:16
|
15 |     let data = [RoadPoint { direction: Direction::East, index: 1 }; 4];
|                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `main::RoadPoint`
|
= note: the `Copy` trait is required because the repeated element will be copied

如何实现 Copy特性?

68100 次浏览

您不必自己实现 Copy; 编译器可以为您派生它:

#[derive(Copy, Clone)]
enum Direction {
North,
East,
South,
West,
}


#[derive(Copy, Clone)]
struct RoadPoint {
direction: Direction,
index: i32,
}

注意,实现 Copy的每个类型也必须实现 Clone.Clone也可以派生。

只需在枚举前面加上 #[derive(Copy, Clone)]即可。

如果你真的想,你也可以

impl Copy for MyEnum {}

派生属性在底层做同样的事情。