当前位置: 首页 > article >正文

rust 的Clone

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

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

#[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

#[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)

#[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 }


http://www.kler.cn/a/589113.html

相关文章:

  • 基于SpringBoot的“考研互助平台”的设计与实现(源码+数据库+文档+PPT)
  • 深度学习中的向量的样子-DCN
  • Leetcode hot 100 191.对称二叉树
  • 2025站群泛目录程序秒收优化新策略(关键词布局与流量分配)
  • 鸿蒙模拟器运行NDK项目失败 9568347
  • 麒麟服务器操作系统Redis部署手册
  • Javaweb后端全局异常处理器
  • Elasticsearch-07-Elasticsearch Java API Client-Elasticsearch 8.0 的高阶api
  • C#的委托Action
  • CSS Table (表格)
  • 批量将多个 Excel 合并成单个文件|批量按文件夹合并 Excel
  • 【Go | 从0实现简单分布式缓存】-7:增加etcd和gRPC功能
  • 【MySQL篇】MySQL内置函数
  • 复现代码常出现的一些报错(pruning)
  • 新型XCSSET恶意软件利用增强混淆技术攻击macOS用户
  • React Vue 项开发中组件封装原则及注意事项
  • 【NLP】7. 自然语言处理 (NLP) 的关键要素
  • 2025年渗透测试面试题总结-某一线实验室实习(题目+回答)
  • 时间序列预测(十九)——卷积神经网络(CNN)在时间序列中的应用
  • DeepSeek 助力 Vue3 开发:打造丝滑的表格(Table)之添加列宽调整功能,示例Table14_13可展开行的固定表头表格