Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement Rust's Copy trait?

Tags:

rust

traits

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?

like image 903
tehnyit Avatar asked Feb 17 '16 13:02

tehnyit


People also ask

Does Option implement copy trait?

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).

Do Rust references implement copy?

Yes, this is correct. In Rust terms, &T is Copy , which means that it can be copied bitwise without transferring ownership.

What is copy trait in Rust?

pub trait Copy: Clone { } Types whose values can be duplicated simply by copying bits.

How do you copy variables in Rust?

You can just use . clone() for your duplicate function.


1 Answers

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.

like image 55
fjh Avatar answered Sep 22 '22 14:09

fjh