如何实现 Rust 的 Copy 特性?

How can I implement Rust's 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 特性:

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 特性?

您不必自己实施 Copy;编译器可以为你导出它:

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

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

请注意,每个实现 Copy 的类型也必须实现 CloneClone也可以导出

只需在您的枚举之前添加 #[derive(Copy, Clone)]

如果你真的想要,你也可以

impl Copy for MyEnum {}

派生属性在幕后做同样的事情。