在 Rust 中:clone() 和 to_owned() 有什么区别,何时使用哪个?
大家好!我最近开始学习 Rust,总是混淆 clone() 和 to_owned() 方法。看起来两者都创建数据的副本,但文档中说它们是不同的东西。在实践中,我看到 clone() 可以在任何实现了 Clone trait 的类型上调用,而 to_owned() 只能在实现了 ToOwned trait 的类型上调用。但这难道不是一回事吗?
下面是一个让我困惑的具体例子:
```rust
let s: &str = "hello";
let a: String = s.to_owned();
let b: String = s.to_string(); // 也能工作
// 为什么我不能写 s.clone() 来得到 String?
// 因为 clone() 返回 &str,而不是 String!
```
另一个例子:我在处理切片。我有一个 &[i32],想得到 Vec。我可以做 slice.to_owned() —— 这能工作。但如果我做 slice.clone(),我得到的又是 &[i32],而不是 Vec。为什么会这样?
我觉得 to_owned() 是一个神奇的方法,它能把借用的数据“变成”拥有所有权的数据。而 clone() 只是复制。