如何实现 Rust 的 Copy 特性? [英] How can I implement Rust's Copy trait?
本文介绍了如何实现 Rust 的 Copy 特性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 Rust 中初始化一个结构数组:
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];
当我尝试编译时,编译器抱怨 Copy
特性没有实现:
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
如何实现 Copy
特性?
推荐答案
您不必实施 复制
自己;编译器可以为您派生:
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,
}
请注意,每个实现 Copy
的类型也必须实现 克隆
.Clone
也可以导出.
Note that every type that implements Copy
must also implement Clone
. Clone
can also be derived.
这篇关于如何实现 Rust 的 Copy 特性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文