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?
Option<&mut T> can't implement Clone or Copy because &mut T doesn't, for lifetime reasons. If the compiler supported some special trait, say BorrowCopyOfPointer , then Option<&mut T> could implement that, as could other wrapper types ( &mut T would implicitly implement it).
Yes, this is correct. In Rust terms, &T is Copy , which means that it can be copied bitwise without transferring ownership.
pub trait Copy: Clone { } Types whose values can be duplicated simply by copying bits.
You can just use . clone() for your duplicate function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With