我正在try 初始化Rust中的一系列 struct :

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 trait:

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

如何实现Copytrait ?

推荐答案

你不必自己实现Copy;编译器可以为您派生它:

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

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

请注意,实现Copy的每个类型也必须实现Clone.Clone也可以导出.

Rust相关问答推荐

为什么迭代器上的`. map(...)`的返回类型如此复杂?

使用Clap时如何将String作为Into Str参数传递?

如何提高自定义迭代器的`extend`性能

这是不是在不造成嵌套的情况下从枚举中取出想要的变体的惯用方法?

S,一般性状和联想型性状有什么不同?

铁 rust 中的泛型:不能将`<;T作为添加>;::Output`除以`{Float}`

如何将映射反序列化为具有与键匹配的字段的定制 struct 的向量?

返回Result<;(),框<;dyn错误>>;工作

使用启用优化的 alloc 会导致非法指令崩溃

try 从标准输入获取用户名和密码并删除 \r\n

Rust:为什么 Pin 必须持有指针?

为什么需要同时为值和引用实现`From`?方法不应该自动解引用或borrow 吗?(2023-06-16)

实现AsyncWrite到hyper Sender时发生生命周期错误

Rust 程序中的内存泄漏

特征中定义的类型与一般定义的类型之间的区别

判断对象是 PyDatetime 还是 Pydate 的实例?

为什么1..=100返回一个范围而不是一个整数?

为什么 &i32 可以与 Rust 中的 &&i32 进行比较?

如何异步记忆选项中的 struct 字段

在 Traits 函数中设置生命周期的问题