Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate string literal with another string

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.

like image 910
Vladimir Matveev Avatar asked Dec 07 '22 08:12

Vladimir Matveev


2 Answers

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";
like image 153
Christopher Davies Avatar answered Jan 17 '23 08:01

Christopher Davies


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);
}
like image 26
Vladimir Matveev Avatar answered Jan 17 '23 08:01

Vladimir Matveev