更新的答案
这是不可能的。一个 String
必须是在内存中单个连续的分配块。如果你想自己实现一个简单的解决方案,可以定义一个类似于以下类型:
struct MyString {
parts: Vec<String>,
}
impl MyString {
fn concat(&mut self, other: String) {
self.parts.push(other);
}
}
然而,重新实现自定义类型的每个有用的`String`方法将变得繁琐且容易出错。您可以找到一个实现了
Rope数据结构的Rust crate,
an-rope 似乎就是这样一个 Crate,但它只支持一小部分`String`方法。
当我将 OP 的问题解释为关于无效化和移动变量时,我给出了此答案:
原始回答
通过将它传递到drop
函数中,您可以将任何非Copy
变量无效化并移动到其他地方:
fn main() {
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2;
drop(s2);
}
如果这是您的应用程序中常见的模式,您可以编写一个函数,该函数接管2个字符串的所有权并返回连接结果。
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);
}
s2
附加到s1
的缓冲区末尾。 - Masklinn