【问题标题】:Why does string concatenation consume only the first string?为什么字符串连接只消耗第一个字符串?
【发布时间】:2021-01-28 15:45:35
【问题描述】:

我在阅读 rust book 时遇到了这个问题:

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
}

事实证明'+ 运算符使用add 方法,其签名看起来像这样':

fn add(self, s: &str) -> String { // ... }

我了解s1 被“使用”并且以后不再可用的原因。但是为什么生锈会这样做呢?我的意思是,为什么add 方法不能引用self (&self) 作为第一个参数,以便s1 字符串可供以后使用?

【问题讨论】:

    标签: rust


    【解决方案1】:

    如果签名是fn add(&self, s:&str),这意味着即使在调用上下文中第一个参数(称为self)可以被使用(因为之后不再使用),add() 函数将 必须首先克隆此字符串,以便使用s 对其进行扩展。

    另一方面,为 self 使用 可以重用原始字符串,无需克隆即可直接扩展它。

    这种情况同时也是最有效和最普遍的,因为如果你真的想保留原始字符串,你总是可以在调用add()之前克隆它。

    fn main() {
        let s1 = String::from("Hello, ");
        let s2 = String::from("world!");
        let s3 = s1 + &s2;
        // println!("s1: {}", s1); // borrow of moved value: `s1`
        println!("s2: {}", s2);
        println!("s3: {}", s3);
        println!("~~~~~~~~~~~~~~~~");
        let s1 = String::from("Hello, ");
        let s2 = String::from("world!");
        let s3 = s1.clone() + &s2;
        println!("s1: {}", s1); // not consumed by +
        println!("s2: {}", s2);
        println!("s3: {}", s3);
    }
    

    【讨论】:

    • 谢谢,我明白了。
    猜你喜欢
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 2016-12-30
    • 2016-01-04
    • 2015-07-25
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    相关资源
    最近更新 更多