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 }

相关推荐
CoderCodingNo2 分钟前
【GESP】C++五级练习题 luogu-P2242 公路维修问题
开发语言·c++·算法
傻啦嘿哟2 分钟前
Python家庭支出统计:从Excel到可视化图表的完整指南
开发语言·python·excel
csbysj20206 分钟前
Ruby 简介
开发语言
YUJIANYUE9 分钟前
asp/php日历式值班查询系统2026版
开发语言·php
FJW0208149 分钟前
Python装饰器
开发语言·python
咸甜适中11 分钟前
双色球、大乐透兑奖分析小程序(rust_Tauri + Vue3 + sqlite)
爬虫·rust·sqlite·vue3·tauri2
Allen_LVyingbo11 分钟前
用Python实现辅助病案首页主诊断编码:从数据清洗到模型上线(下)
开发语言·python·安全·搜索引擎·知识图谱·健康医疗
忠实米线12 分钟前
使用lottie.js播放json动画文件
开发语言·javascript·json
CS创新实验室15 分钟前
《计算机网络》深入学:虚拟局域网(VLAN)技术与应用
开发语言·计算机网络·php·vlan·虚拟局域网
H Corey16 分钟前
Java抽象类与接口实战指南
java·开发语言·学习·intellij-idea