如何为包含String字段(或任何非Copy类型)的结构体实现Copy和Clone?
大家好!我刚开始学习Rust,遇到了一个两天都没解决的问题。我正在编写一个简单的用户管理程序,有以下结构体:
```rust
struct User {
id: u32,
name: String,
email: String,
}
```
我需要这个结构体能够被复制并传递给函数而不需要借用——也就是说我想为它实现`Copy`和`Clone` trait。但是当我写`#[derive(Copy, Clone)]`时,编译器报错:
```
error[E0204]: the trait `Copy` may not be implemented for this type
--> src/main.rs:1:10
|
1 | #[derive(Copy, Clone)]
| ^^^^
2 | struct User {
3 | name: String,
| ---- this field does not implement `Copy`
```
我明白`String`没有实现`Copy`,因为它是动态分配内存的类型。但怎样才能让这个结构体可复制呢?在C++中我只需写一个拷贝构造函数,但这里更复杂。
我需要写