我正在尝试在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
特质?
#[derive(Clone, Copy)]
是正确的方式,但需要说明的是,它并不神奇:手动实现这些特性很容易,尤其是像你这样简单的情况:impl Copy for Direction {} impl Clone for Direction { fn clone(&self) -> Self { *self } }
。 - user395760