Ik probeer een reeks structs in Rust te initialiseren:
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];
Als ik probeer te compileren, klaagt de compiler dat de eigenschap Copy
niet is geïmplementeerd:
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
Hoe kan de eigenschap Copy
worden geïmplementeerd?
Antwoord 1, autoriteit 100%
U hoeft Copy
jezelf; de compiler kan het voor je afleiden:
#[derive(Copy, Clone)]
enum Direction {
North,
East,
South,
West,
}
#[derive(Copy, Clone)]
struct RoadPoint {
direction: Direction,
index: i32,
}
Merk op dat elk type dat Copy
implementeert, ook Clone
. Clone
kan ook worden afgeleid.
Antwoord 2, autoriteit 23%
Zet gewoon #[derive(Copy, Clone)]
voor je opsomming.
Als je echt wilt, kun je ook
impl Copy for MyEnum {}
Het derive-attribuut doet hetzelfde onder de motorkap.