string - 如何在不复制的情况下将两个字符串连接成第三个字符串?

标签 string rust concatenation move ownership

我是 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
}

是否有可能不仅取得 s1 的所有权,而且取得 s2 的所有权,所以 s2 一样无效s1,使 s3 成为唯一可用的变量?

最佳答案

更新的答案

这是不可能的。 String 必须是内存中的单个连续分配。如果您想推出自己的简单解决方案,您可以定义这样的类型:

struct MyString {
    parts: Vec<String>,
}

impl MyString {
    fn concat(&mut self, other: String) {
        self.parts.push(other);
    }
}

然而,为这个自定义类型重新实现每个有用的 String 方法将是乏味且容易出错的。你可以找到一个实现 Rope data structure 的 Rust crate。 , 和 an-rope似乎是这样一个 crate ,但只支持一小部分 String 方法。


当我将 OP 的问题解释为关于使变量无效和 move 的问题时,我给出了这个答案:

原始答案

您可以通过将任何非Copy 变量 move 到其他地方来使其无效,例如将其传递给 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
}

如果这是您应用程序中的常见模式,您只需编写一个函数,它获取 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
}

关于string - 如何在不复制的情况下将两个字符串连接成第三个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66187643/

相关文章:

rust - 如何根据整数格式化带缩进的字符串?

macros - 匹配 nom 中的几个字节之一

java - 关于字符串相似性度量的建议 (Java)。距离,听起来像还是组合?

创建 C 格式的字符串(不打印它们)

rust - 如何正确处理来自Rust中maxminddb::geoip2的AddressNotFound错误?

VBA:&和+之间的区别

javascript - 有条件地分割和连接文本

SQL UPDATE 带有附加字符串 CONCAT 的字段中的所有值不起作用

python - 如何删除以某物开头和结尾的子字符串?

python - 如何检查python中包含的列表中的项目