我想在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];
Run Code Online (Sandbox Code Playgroud)
当我尝试编译时,编译器抱怨该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
Run Code Online (Sandbox Code Playgroud)
如何Copy实施这一特性?
fjh*_*fjh 33
你不必Copy自己实施; 编译器可以为您派生它:
#[derive(Copy, Clone)]
enum Direction {
North,
East,
South,
West,
}
#[derive(Copy, Clone)]
struct RoadPoint {
direction: Direction,
index: i32,
}
Run Code Online (Sandbox Code Playgroud)
请注意,实现的每个类型也Copy必须实现Clone.Clone也可以派生出来.
llo*_*giq 10
只是#[derive(Copy, Clone)]在你的枚举之前.
如果你真的想要,你也可以
impl Copy for MyEnum {}
Run Code Online (Sandbox Code Playgroud)
derive-attribute在幕后做同样的事情.