在 C++ 中,我们可以这样做:
std::string ar[2] = {std::string("hello"), std::string("world")};
std::string hello = ar[0];
std::string world = ar[1];
Run Code Online (Sandbox Code Playgroud)
和hello最终world成为新的字符串。我认为这是因为=operator它的实现就像clone()Rust 中的 a 一样。
在 Rust 中,这看起来像这样:
let ar = vec![String::from("hello"), String::from("world")]
let hello = ar[0].clone();
let world = ar[1].clone();
Run Code Online (Sandbox Code Playgroud)
这很快就会变得非常重复。
是否可以克隆=对象,这看起来像是自然行为?
eff*_*ect 12
简短的回答:不。在 Rust 中,赋值运算符具有移动语义,除非类型实现了该Copy特征。
String没有实现该Copy特征,但它确实实现了该Clone特征(这就是我们可以使用 的原因clone())。但这是为什么呢?
这是语言设计者有意的选择。无法通过简单的按位复制进行复制的类型(String例如,其中包含在堆上分配的缓冲区)不允许实现该Copy特征。语言设计者希望程序员能够清楚哪些类型可以通过按位复制“廉价”地复制,哪些类型复制起来成本更高。
| 归档时间: |
|
| 查看次数: |
510 次 |
| 最近记录: |