【问题标题】:Concatenate string literal with another string将字符串文字与另一个字符串连接起来
【发布时间】:2013-04-14 08:37:32
【问题描述】:

我不能将字符串文字与字符串变量连接起来有什么原因吗?以下代码:

fn main() {
    let x = ~"abcd";
    io::println("Message: " + x);
}

给出这个错误:

test2.rs:3:16: 3:31 error: binary operation + cannot be applied to type `&'static str`
test2.rs:3     io::println("Message: " + x);
                           ^~~~~~~~~~~~~~~
error: aborting due to previous error

我想这是一个非常基本且非常常见的模式,在这种情况下使用 fmt! 只会带来不必要的混乱。

【问题讨论】:

    标签: string concatenation rust


    【解决方案1】:

    在最新版本的 Rust (0.11) 中,波浪号 (~) 运算符已被弃用。

    以下是如何使用 0.11 版修复它的示例:

    let mut foo = "bar".to_string();
    foo = foo + "foo";
    

    【讨论】:

    • 抱歉,我不知道如何将您的答案应用于该问题。您能否展示如何实现他的实际 abcd 和 Message 示例?
    • 为什么 String 可以和 &str 连接,而不是 2 个字符串?
    【解决方案2】:

    默认情况下,字符串字面量具有静态生命周期,并且无法连接唯一向量和静态向量。使用唯一的文字字符串有帮助:

    fn main() {
        let x = ~"abcd";
        io::println(~"Message: " + x);
    }
    

    【讨论】:

      【解决方案3】:

      只是添加到上面的答案,只要最右边的字符串是 ~str 类型,那么你可以添加任何类型的字符串。

      let x = ~"Hello" + @" " + &"World" + "!";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-12
        • 1970-01-01
        • 2022-08-04
        • 2020-10-01
        • 2017-03-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多