Concatenate string literal with another string

被刻印的时光 ゝ 提交于 2019-12-10 16:24:58

问题


Is there some reason why I cannot concatenate a string literal with a string variable? The following code:

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

gives this error:

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

I guess this is a pretty basic and very common pattern, and usage of fmt! in such cases only brings unnecessary clutter.


回答1:


With the latest version of Rust (0.11), the tilde (~) operator is deprecated.

Here's an example of how to fix it with version 0.11:

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



回答2:


By default string literals have static lifetime, and it is not possible to concatenate unique and static vectors. Using unique literal string helped:

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



回答3:


Just to addon to the above answer, as long as the right most string is of the type ~str then you can add any kind of string to it.

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


来源:https://stackoverflow.com/questions/15997206/concatenate-string-literal-with-another-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!