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 }

相关推荐
Tiger Z1 小时前
R 语言科研绘图 --- 密度图-汇总
开发语言·程序人生·r语言·贴图
叶雅茗2 小时前
PHP语言的区块链扩展性
开发语言·后端·golang
双叶8363 小时前
(C语言)写一个递归函数DigitSum(n),输入一个非负整数,返回组成它的数字之和(递归函数)
c语言·开发语言·数据结构·算法·游戏
“抚琴”的人4 小时前
C#—线程池详解
开发语言·c#
信徒_4 小时前
java 中判断对象是否可以被回收和 GCROOT
java·开发语言·jvm
胖哥真不错4 小时前
Python基于Django和协同过滤算法实现电影推荐系统功能丰富版
开发语言·python·django·项目实战·电影推荐系统·协同过滤算法·功能丰富版
weixin_307779135 小时前
Python和Docker实现AWS ECR/ECS上全自动容器化部署网站前端
开发语言·python·云计算·aws
Ttang235 小时前
SpringBoot(4)——SpringBoot自动配置原理
java·开发语言·spring boot·后端·spring·自动配置·原理
苏雨流丰5 小时前
Java中按照不同字段进行排序
java·开发语言
神仙别闹5 小时前
基于Java+MySQL实现的医药销售管理系统
java·开发语言·mysql