简体   繁体   中英

How can I implement Rust's Copy trait?

I am trying to initialise an array of structs in 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]; 

When I try to compile, the compiler complains that the Copy trait is not implemented:

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

How can the Copy trait be implemented?

You don't have to implement Copy yourself; the compiler can derive it for you:

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

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

Note that every type that implements Copy must also implement Clone . Clone can also be derived.

Just prepend #[derive(Copy, Clone)] before your enum.

If you really want, you can also

impl Copy for MyEnum {}

The derive-attribute does the same thing under the hood.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM