70 %
Chris Biscardi

Concatenating two string slices &str in Rust

When concatenating two string slices, we can't use + in Rust.

rust
fn main() {
let one = "string";
let two = "something else";
let three = one + two;
}

The compiler will warn us.

error[E0369]: cannot add `&str` to `&str`
--> main.rs:5:19
|
5 | let three = one + two;
| --- ^ --- &str
| | |
| | `+` cannot be used to concatenate two `&str` strings
| &str
|
help: `to_owned()` can be used to create an owned `String` from a string reference. String concatenation appends the string on the right to the string on the left and may require reallocation. This requires ownership of the string on the left
|
5 | let three = one.to_owned() + two;
| ^^^^^^^^^^^^^^

As the compiler help text describes, concatenation appends the string on the right to the string on the left, which requires ownership and a string slice is not an owned type.

Instead, we can take advantage of the format! macro to leave both string slices alone and create a new String.

rust
format!("{}{}", one, two);
rust
fn main() {
let one = "string";
let two = "something else";
let three = format!("{}{}", one, two);
}