rust 的Clone

CloneRust 编程语言中一个核心特质(trait), 定义了类型如何安全、明确地创建其值的深拷贝(deep copy)。

下面用实例来演示Clone的作用,先看一下如下的代码,注意此代码编译不过。

rust 复制代码
#[derive(Debug)]
struct Item{
    value: i32,
}

fn main() {
    let a = Item{value:7};
    let b = a;
    println!("value a {:?}, value b {:?}", a, b);
}

编译报错:

cargo run

error[E0382]: borrow of moved value: `a`

--> src/main.rs:10:44

|

8 | let a = Item{value:7};

| - move occurs because `a` has type `Item`, which does not implement the `Copy` trait

9 | let b = a;

| - value moved here

10 | println!("value a {:?}, value b {:?}", a, b);

| ^ value borrowed here after move

|

note: if `Item` implemented `Clone`, you could clone the value

--> src/main.rs:3:1

|

3 | struct Item{

| ^^^^^^^^^^^ consider implementing `Clone` for this type

...

9 | let b = a;

| - you could clone this value

= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0382`.

报错的意思是变量a的所有权已经被移动到b,所以println!无法再使用a。

如果要想Item类的变量赋值后所有权继续有效,就需要Item类实现clone()。

方案一:手动为Item类实现trait Clone

rust 复制代码
#[derive(Debug)]
struct Item{
    value: i32,
}

impl Clone for Item{
    fn clone(&self) -> Self{
        Item { value: self.value, }
    }
}

fn main() {
    let a = Item{value:7};
    let b = a.clone();
    println!("value a {:?}, value b {:?}", a, b);
}

编译运行:

Running `target\debug\greeting.exe`

value a Item { value: 7 }, value b Item { value: 7 }

方案二:

使用属性(Attribute)

rust 复制代码
#[derive(Debug, Clone)]
struct Item{
    value: i32,
}


fn main() {
    let a = Item{value:7};
    let b = a.clone();
    println!("value a {:?}, value b {:?}", a, b);
}

编译运行

Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s

Running `target\debug\greeting.exe`

value a Item { value: 7 }, value b Item { value: 7 }

相关推荐
好多173 分钟前
《Java中的IO流》
java·开发语言·php
MetaverseMan30 分钟前
Golang单例模式和工厂模式详解
开发语言·golang·适配器模式
杏花春雨江南44 分钟前
Spring Cloud Gateway 作为一个独立的服务进行部署吗
java·开发语言
GSDjisidi1 小时前
东京本社招聘 | 财务负责人 & 多个日本IT岗位(Java/C++/Python/AWS 等),IT营业同步招募
java·开发语言·aws
skywalk81631 小时前
copyparty 是一款使用单个 Python 文件实现的内网文件共享工具,具有跨平台、低资源占用等特点,适合需要本地化文件管理的场景
开发语言·python
BYSJMG1 小时前
计算机毕设选题:基于Python+MySQL校园美食推荐系统【源码+文档+调试】
大数据·开发语言·python·mysql·django·课程设计·美食
Zz_waiting.1 小时前
案例开发 - 日程管理 - 第七期
开发语言·前端·javascript·vue.js·html·路由
writeone1 小时前
9-10关于JS初学产生的问题
开发语言·javascript·ecmascript
索迪迈科技2 小时前
Flink Task线程处理模型:Mailbox
java·大数据·开发语言·数据结构·算法·flink
longxiangam3 小时前
墨水屏程序
单片机·嵌入式硬件·rust·risc-v