We can concatenate Strings in any programming language, including Rust, and we do it a lot. No programming language does not deal with string concatenation. However, Rust is different as it has two types of strings – String and str. Also, we need to declare a mutable string variable to append another string to it.
String functions to Concatenate Strings in Rust
String literals in Rust are always of type str and the original string values are immutable. Consider the following examples.
1 | let person_name:&str = "karl"; |
None of the functions available to the variable person_name modifies the string value “karl” content. Even the trim() function only returns a slice of the original data.
1 2 3 4 5 | // prints out "karl|" println!("{}|", name.trim()); // prints out "karl |" println!("{}|", name); |
String concatenation in Rust only works with String type (even when using the “+” sign). Here are some examples of string concatenation in Rust using the String type.
1 2 3 4 5 6 7 8 | let mut full_name: String = String::from("Karl"); full_name.push_str(" "); full_name.push_str("S"); full_name.push_str(" "); full_name.push_str("G"); println!("{}", full_name); |
Alternatively, we can use the + operator to concatenate strings in Rust. However, the left-side operand must be a reference of String type.
1 2 3 | let mut first_name: String = String::from("Karl"); let mut full_name = first_name + " " + "S" + " " + "G"; println!("{}", full_name); |
What happens if first_name was of an str type? Let’s modify the Rust codes a little bit as follows.
1 2 3 | let mut first_name: &str = "Karl"; let mut full_name = first_name + " " + "S" + " " + "G"; println!("{}", full_name); |
When we run these codes, we will get the following errors at compile time in an attempt to concatenate strings of str type in Rust.
1 2 3 4 5 6 7 8 9 10 11 12 13 | error[E0369]: cannot add `&str` to `&str` --> src\main.rs:8:36 | 8 | let mut full_name = first_name + " " + "S" + " " + "G"; | ---------- ^ --- &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 | 8 | let mut full_name = first_name.to_owned() + " " + "S" + " " + "G"; | ~~~~~~~~~~~~~~~~~~~~~ |
To fix the Rust codes, we need to use one of the String functions available to the first_name variable that converts an str string to String type. For example, we could use the to_owned function.