- 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.
- 數據存儲架構與技術
- 有趣的二進制:軟件安全與逆向分析
- Visual Studio 2015 Cookbook(Second Edition)
- Modern Programming: Object Oriented Programming and Best Practices
- 工業大數據分析算法實戰
- Libgdx Cross/platform Game Development Cookbook
- Python醫學數據分析入門
- 跟老男孩學Linux運維:MySQL入門與提高實踐
- Oracle PL/SQL實例精解(原書第5版)
- 計算機應用基礎教程上機指導與習題集(微課版)
- PostgreSQL指南:內幕探索
- R語言數據挖掘
- 數字IC設計入門(微課視頻版)
- Python數據分析從小白到專家
- 大數據數學基礎(Python語言描述)