Hoe kan ik Rust’s Copy-eigenschap implementeren?

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 Copyniet 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 Copyworden geïmplementeerd?


Antwoord 1, autoriteit 100%

U hoeft Copyjezelf; 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 Copyimplementeert, ook Clone. Clonekan 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.

Other episodes