String 将字符串文字与另一个字符串连接

String 将字符串文字与另一个字符串连接,string,concatenation,rust,String,Concatenation,Rust,有什么原因不能将字符串文字与字符串变量连接起来吗?以下代码: 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);

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

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的用法在这种情况下只会带来不必要的混乱。

默认情况下,字符串文字具有静态生存期,并且不可能连接唯一和静态向量。使用唯一文字字符串有助于:

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

为了补充上面的答案,只要最右边的字符串是~str类型,就可以向其中添加任何类型的字符串

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

在最新版本的Rust(0.11)中,不推荐使用tilde(
~
)运算符

以下是如何使用版本0.11修复此问题的示例:

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

对不起,我不知道如何应用你的答案来回答这个问题。您能演示一下如何实现他的实际abcd和消息示例吗?为什么字符串可以与&str连接,但不能与两个字符串连接?