cr7*_*gu3 3 string move concatenation ownership rust
我是 Rust 新手,目前正在阅读《Rust 编程语言》一书。
我对这个例子很好奇:
fn main() {
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used
}
Run Code Online (Sandbox Code Playgroud)
是否有可能不仅拥有 的所有权s1,而且还拥有 的所有权s2,因此s2也变得无效,从而s1成为s3唯一仍然可用的变量?
更新答案
这不可能。AString必须是内存中的单个连续分配。如果您想推出自己的简单解决方案,您可以定义如下类型:
struct MyString {
parts: Vec<String>,
}
impl MyString {
fn concat(&mut self, other: String) {
self.parts.push(other);
}
}
Run Code Online (Sandbox Code Playgroud)
然而,为这种自定义类型重新实现每个有用的String方法将是乏味且容易出错的。你可以找到一个实现Rope 数据结构的Rust 箱子,而an-rope似乎就是这样的箱子,但只String支持一小部分方法。
当我将OP的问题解释为关于使变量无效和移动的问题时,我给出了这个答案:
原答案
您可以Copy通过将任何非变量移动到其他地方来使其无效,例如将其传递给drop函数:
fn main() {
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // s1 invalidated
drop(s2); // s2 invalidated
// now only s3 is usable
}
Run Code Online (Sandbox Code Playgroud)
如果这是应用程序中的常见模式,您只需编写一个函数,该函数获取 2 的所有权String并返回连接结果:
fn concat(s1: String, s2: String) -> String {
s1 + &s2
}
fn main() {
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = concat(s1, s2); // s1 & s2 invalidated
// now only s3 is usable
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3162 次 |
| 最近记录: |