rust 的Clone

Clone 是 Rust 编程语言中一个核心特质(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

errorE0382: 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 }

相关推荐
学逆向的18 分钟前
C 数据溢出与精度丢失
c语言·开发语言·网络安全
霸道流氓气质1 小时前
AgentFlow 入门与实战:Task-Based 并发、EWMA 动态调度与四道门禁的 Java 生产级编排
java·开发语言
释厄6232 小时前
错误无误公理——错误正确本同源都迭代定律——逆转有价值
android·开发语言·kotlin
2601_962885722 小时前
如何用 Python计算 CR能量指标(中间意愿指标)?
开发语言·python
临床数据科学和人工智能兴趣组2 小时前
在R语言的生态系统中,字符串处理一直是一个重要且复杂的任务
开发语言·正则表达式·r语言·r语言-4.2.1
蜗牛互联网2 小时前
Python调用Gemini Structured Outputs实现工单路由门禁
java·开发语言·人工智能·python
SEO_juper3 小时前
给网页做可引用性评分:判断内容够不够让 AI 引用(GEO 工具,附代码)
开发语言·人工智能·爬虫·python·seo·独立站
Wang's Blog3 小时前
Java 项目实战: 交友项目 - 产品定位、功能模块与客户端原型解读
java·开发语言·交友
Source.Liu3 小时前
【A11】拥有者模式平台架构笔记
windows·笔记·架构·rust
盛世宏博北京3 小时前
十二防档案库房总线架构设计:恒湿消毒净化一体机 RS485 组网实战笔记
开发语言·笔记·php·恒湿机·档案八防温湿度