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 }

相关推荐
Han_han91914 分钟前
常用API:
java·开发语言
minji...18 分钟前
Linux 线程同步与互斥(四) POSIX信号量,基于环形队列的生产者消费者模型
linux·运维·服务器·c语言·开发语言·c++
Highcharts.js28 分钟前
在 React 中使用 useState 和 @highcharts/react 构建动态图表
开发语言·前端·javascript·react.js·信息可视化·前端框架·highcharts
likerhood43 分钟前
java中的return this、链式编程和Builder模式
java·开发语言
浪客川1 小时前
【百例RUST - 014】Trait
服务器·网络·rust
shimly1234561 小时前
RUST impl <T> Wrapper <T>
rust
原来是猿1 小时前
Linux线程同步与互斥(三):POSIX信号量与环形队列生产者消费者模型
linux·运维·服务器·开发语言
未来转换1 小时前
基于A2A协议的生产应用实践指南(Java)
java·开发语言·算法·agent
Rust语言中文社区1 小时前
【Rust日报】Clone:像进程一样 fork 虚拟机的 Rust KVM VMM
开发语言·后端·rust
求知也求真佳1 小时前
S02|工具使用:让 Agent 真正会干活,添加工具
开发语言·agent