In Rust there are several different ways to concatenate strings depending on whether you're working with &str
, String
, or a combination of both.
+
OperatorIn the context of string concatenation, the +
operator takes ownership of the left-hand String
and appends the borrowed right-hand &str
.
let a = String::from("Hello, ");
let b = "world!";
let result = a + b;
println!("{}", result); // "Hello, world!"
// Note: `a` is moved and can’t be used afterward
If you have two String
s and want to use +
concatenation, you'll need to provide a reference to the string you want to append as the right hand.
let a = String::from("Hello, ");
let b = String::from("world!");
let result = a + &b;
push_str
for Mutable StringsIf you have mutable access to a String
, you can append to it directly with push_str
. This changes the contents of the String
.
let mut s = String::from("Hello");
s.push_str(", world");
s.push('!'); // .push is for characters only
println!("{}", s); // "Hello, world!"
format!
MacroWhen you need to join more than two strings or want to avoid moving ownership, use format!
.
let a = "Hello";
let b = String::from(", ");
let c = "world!";
let result = format!("{}{}{}", a, b, c);
println!("{}", result); // "Hello, world!"
// No variables are moved – all can be reused
In summary, with the +
operator or push_str
, you will need to own the string you are appending to (meaning you may have to perform an allocation via to_string
or other if you don't already own it). format!
is more flexible and useful when you want to avoid taking ownership, or are performing multiple/complex concatenations.