- Hands-On Data Structures and Algorithms with Rust
- Claus Matzinger
- 293字
- 2021-07-02 14:11:49
Copying and cloning
In Chapter 1, Hello Rust!, we discussed Send, a marker trait that allows a type to be "sent" across multiple threads. Something that's similar but less complex is local moving, which commonly occurs in a program—for example, when you pass a variable into a function.
Copying and cloning, on the other hand, happen on different occasions. When a variable is assigned to another variable, the compiler will typically copy the value implicitly, which can be done safely and cheaply for stack-allocated variables.
Cloning is always a deep copy of a type—implemented either manually (with the Clone trait) or by using the derive macro. Then, cloning is only a matter of invoking the clone() function, an operation that is not necessarily cheap. The following snippet illustrates these two operations:
let y = 5;
let x = y; // Copy
let a = Rc::new(5);
let b = a.clone(); // Clone
The regular usage of these traits and operations is usually intuitive and there isn't much that can go wrong. Usually the compiler clearly states the need for a Copy implementation.
While copying and cloning are great for providing ownership to multiple scopes, they are required when working with immutable storage.
- GitHub Essentials
- Hands-On Data Structures and Algorithms with Rust
- 算法競賽入門經典:習題與解答
- Creating Dynamic UIs with Android Fragments(Second Edition)
- 大數據Hadoop 3.X分布式處理實戰
- 軟件成本度量國家標準實施指南:理論、方法與實踐
- 數據庫原理與應用(Oracle版)
- OracleDBA實戰攻略:運維管理、診斷優化、高可用與最佳實踐
- Spark大數據編程實用教程
- 網站數據庫技術
- 一本書講透Elasticsearch:原理、進階與工程實踐
- Power BI智能數據分析與可視化從入門到精通
- 改變未來的九大算法
- 數據庫查詢優化器的藝術:原理解析與SQL性能優化
- 信息融合中估計算法的性能評估