Rust, Software Development

How To Concatenate Strings in Rust

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.

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.

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.

Alternatively, we can use the + operator to concatenate strings in Rust. However, the left-side operand must be a reference of String type.

What happens if first_name  was of an str type? Let’s modify the Rust codes a little bit as follows.

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.

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.





Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like