This tutorial will go through concatenating strings and describe the two types of strings in Rust.
Table of contents
- Strings in Rust
- Concatenate Strings in Rust using push_str()
- Concatenate Strings in Rust using format!()
- Concatenate Strings in Rust using + operator
- Concatenate Strings in Rust using join() on an array
- Concatenate Strings in Rust using concat!()
- Concatenate Strings in Rust using concat() on an Array
- Summary
Strings in Rust
There are two types of strings in Rust, string
String slice denoted by &str and String.
Both String and &str are groupings of characters. The differences are:
- How they are stored in memory
- How the programmer uses them
Strings are held on the heap, which allows them to be mutable. &str is meant to be immutable and can be a reference to heap data or allocated on the stack or embedded in the code. We can translate between String and &str in a program.
The String is suitable for mutating and holding information longer than the stack can. &str is excellent for runtime speed.
Concatenate Strings in Rust using push_str()
In this example, we are using the push_str on a String. We need to declare a mutable string variable to append another string. Let’s look at the concatenation of String and &str
fn main() {
let mut owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";
owned_string.push_str(borrowed_string);
println!("{}", owned_string);
}
The use of to_owned() converts a string literal to a String. Let’s run the code to see the result:
hello world
We can also use push_str() to concatenate String and String by dereferencing the second String to a string literal using an ampersand (&). Let’s look at the code:
fn main() {
let mut owned_string: String = "hello ".to_owned();
let second_owned_string: String = "world".to_owned();
owned_string.push_str(&second_owned_string);
println!("{}", owned_string);
}
Let’s run the code to see the result:
hello world
Concatenate Strings in Rust using format!()
We can use the format! macro to concatenate two immutable input variables. The first argument of the macro is a format string, which must be a string literal and can contain {}. The additional parameters replace the {} within the format string in the order given unless named or we use positional parameters. Let’s look at the use of format! to concatenate &str and &str
fn main() {
let borrowed_string: &str = "hello ";
let another_borrowed_string: &str = "world";
let full_string = format!("{}{}", borrowed_string, another_borrowed_string);
println!("{}", full_string);
}
Let’s run the code to get the result:
hello world
We can also use the format! macro to concatenate String and String, let’s look at the code:
fn main() {
let owned_string: String= "hello ".to_owned();
let second_owned_string: String= "world".to_owned();
let full_string = format!("{}{}", owned_string, second_owned_string);
println!("{}", full_string);
}
Let’s run the code to get the result:
hello world
Concatenate Strings in Rust using + operator
We can implement the Add trait to concatenate two strings. The + operator consumes the String on the left-hand side and re-uses its buffer (and grows it if necessary). This method avoids allocating a new String and copying the entire contents on every operation. The string on the right-hand side is borrowed; its contents are copied into the returned string. Let’s look at an example with String and &str:
fn main() {
let owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";
let full_string = owned_string + borrowed_string;
println!("{}", full_string);
}
Let’s run the code to get the result:
hello world
If we want to keep using the first String, we can clone it and append it to the clone instead. Let’s look at how to do that:
fn main() {
let owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";
let full_string = owned_string.clone() + borrowed_string;
println!("{}", full_string);
}
Let’s run the code to get the result:
hello world
We can also concatenate &str &str by converting the &str on the left-hand side to a String with to_string().
fn main() {
let borrowed_string: &str = "hello ";
let another_borrowed_string: &str = "world";
let full_string = borrowed_string.to_string() + another_borrowed_string;
println!("{}", full_string);
}
Let’s run the code to get the result:
hello world
Concatenate Strings in Rust using join() on an array
We can implement the function join to concatenate strings. Let’s look at the code:
fn main() {
let a: &str = "hello";
let b: &str = "world";
let result = [a, b].join(" ");
print!("{}", result);
}
The join trait flattens the string slice [a, b] into a single string, placing the specified separator between each. Let’s run the code to see the result:
hello world
Concatenate Strings in Rust using concat!()
We can implement the concat! macro to concatenate strings. The macro concatenates literals into a static string slice. Let’s look at the code:
fn main() {
println!("{}", concat!("hello ", "world"));
}
Let’s run the code to see the result:
hello world
Concatenate Strings in Rust using concat() on an Array
We can concatenate strings using the concat function on an array. The concat function takes a slice as an argument and flattens it into a single value, similar to the join function.
Let’s look at an example:
fn main() {
let a = "hello ";
let b = "world";
let c =[a, b].concat();
println!("{}", c)
}
Let’s run the code to see the result:
hello world
Summary
Congratulations on reading to the end of this tutorial! We have gone through the various ways to concatenate strings in Rust.
For further reading on Rust, go to the articles:
- How to Do Bubble Sort in Rust
- How to Split a String in Rust
- How to Convert String to Integer and Float in Rust
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.
