Concat. Consider a string in Rust: we can loop over its characters, test its length, or add additional data to it. The term "concat" refers to a way to add data to a string.
In Rust, the String struct contains a growable buffer. This is managed by the type itself, so we do not need to write this code ourselves. This buffer is useful when concatenating.
Concat example. To start, we see 3 different ways to concatenate strings. With "to_owned" we get a String instance from a str reference. This is needed to have a growable buffer.
Note We can use the plus sign to add a string to the leftmost String. A str reference can be added to a String.
Note 2 Push_str appends a str reference to the end of the current String. It is like a concat, add, or append function.
fn main() {
let left = "string1";
let right = "string2";
// Use add operator.
let result1: String = left.to_owned() + right;
println!("{result1}");
// Use new and push_str.
let mut result2 = String::new();
result2.push_str(left);
result2.push_str(right);
println!("{result2}");
// Use from and push_str.
let mut result3 = String::from(left);
result3.push_str(right);
println!("{result3}");
}string1string2
string1string2
string1string2
Capacity benchmark. In Rust the String type is like a StringBuilder from other languages—String has a growable buffer. This optimizes repeated appends.
Version 1 This version of the code adds a str reference to the result String many times.
Version 2 Here we have the same code as version 1, but we use with_capacity to avoid having to resize the underlying buffer.
Result Using with_capacity gives a small performance boost, but even without a capacity, the String handles many appends in an efficient way.
Tip Consider using with_capacity to optimize repeated concatenations to a String.
use std::time::*;
const MAX: usize = 20000000;
fn main() {
// Version 1: use no capacity.
let t0 = Instant::now();
let mut result1 = String::new();
for _ in 0..MAX {
result1 += "abc";
}
println!("{}", t0.elapsed().as_millis());
// Version 2: use with_capacity.
let t1 = Instant::now();
let mut result2 = String::with_capacity(MAX * 3);
for _ in 0..MAX {
result2 += "abc";
}
println!("{}", t1.elapsed().as_millis());
println!("{} {}", result1.len(), result2.len());
}16 ms
13 ms (with_capacity)
60000000 60000000
We can concat Strings with plus or push_str. For repeated concats, using a capacity can improve performance, but Strings support concatenation in an optimized way.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 30, 2025 (edit).