Sub topic 6
Joining text with +, format!, and join
This chapter assumes you know the difference between &str and String, how ownership moves a value, and how to call methods that return Option or Result. It covers the main ways to combine text into a new String, what each way costs, and how to pick one.
The + operator
+ on strings is impl Add<&str> for String. The left operand must be an owned String. The right operand must be a &str. The operator takes the left String by value, appends the right side to its buffer, and returns that same String.
fn main() {
let a = String::from("tic");
let b = String::from("tac");
let c = a + "-" + &b;
let d = format!("{c}-toe");
println!("{d}");
println!("{b}");
}This prints tic-tac-toe and then tac. Three details matter here:
ais moved into the expression. Usingaafter that line is a compile error.&bhas type&String, not&str. The compiler converts it through deref coercion, so the call works.bis only borrowed and stays usable.a + "-" + &bis evaluated left to right.(a + "-")returns aString, and thatStringbecomes the left side of the second+.
Two forms do not compile. "a" + "b" fails because the left side is a &str, and &str has no Add implementation. a + b fails when b is a String, because the right side must be a reference. The fix for both is to make the left side a String and borrow the right side.
Because + reuses the left buffer, a chain of + allocates only when the buffer has to grow. It is cheap, but it consumes its first operand. That makes it awkward when you still need the original.
The += operator
+= is AddAssign<&str> for String. It appends in place and needs no move.
fn main() {
let mut s = String::from("a");
s += "b";
s += &String::from("c");
s.push_str("d");
println!("{s}");
}This prints abcd. s += x and s.push_str(x) do the same work. Use whichever reads better.
format! for mixed content
format! works like println! but returns a String instead of printing. It borrows all of its arguments, so nothing is moved. It also converts non-string values such as numbers through their Display or Debug implementations.
fn main() {
let name = "Ferris";
let age = 7;
let s = format!("{name:>8}|{age:03}|{:.2}", 3.14159);
println!("{s}");
}This prints Ferris|007|3.14. The pieces are:
{name:>8}captures the variablenamefrom scope and right-aligns it in a field 8 characters wide.{age:03}pads the number with zeros to width 3.{:.2}takes the next positional argument and prints two decimal places.
Inline captures ({name}) and positional arguments can appear in the same format string. Only plain identifiers can be captured inline. An expression such as {user.name} is not allowed, so pass it as a positional argument: format!("{}", user.name).
Use {:?} for Debug output. It is useful for strings with quotes or escapes, because it shows them escaped.
join and concat on slices
When you have a collection of pieces, join is clearer than a loop. It is defined on slices of strings, so it works on Vec<&str>, Vec<String>, and arrays. It inserts a separator between elements and not after the last one.
fn main() {
let words = vec!["red", "green", "blue"];
println!("{}", words.join(", "));
println!("{}", words.concat());
let owned: Vec<String> = words.iter().map(|w| w.to_uppercase()).collect();
println!("{}", owned.join("-"));
}The output is:
red, green, blue
redgreenblue
RED-GREEN-BLUEjoin computes the total length first and allocates once. That makes it faster than building the result with repeated + on a string that keeps reallocating. concat is join with an empty separator.
join is a method on slices, not on iterators. If you have an iterator, collect it into a Vec first. If you only want to glue strings together with no separator, you can collect directly into a String:
fn main() {
let parts = vec!["x", "y", "z"];
let t: String = parts.into_iter().collect();
println!("{t}");
}This prints xyz. String implements FromIterator for &str, String, and char, so you can also collect an iterator of char values.
Writing into an existing String with write!
The write! and writeln! macros send formatted text to any destination that implements a write trait. String implements std::fmt::Write, so you can format straight into a buffer without making a temporary String each time.
use std::fmt::Write;
fn main() {
let mut out = String::new();
for i in 1..=3 {
write!(out, "[{i}]").unwrap();
}
writeln!(out, " done").unwrap();
print!("{out}");
}This prints [1][2][3] done. Writing to a String cannot fail in practice, but the macros still return fmt::Result, so you must handle it. Calling unwrap() is acceptable here.
The import matters. std::fmt::Write is for text and works on String. std::io::Write is for bytes and works on files and sockets. If you import the wrong one, write!(out, ...) on a String fails to compile. If you need both traits in one file, import them under different names, for example use std::fmt::Write as _;.
Choosing a method
The right tool depends on what you are combining and whether you need the originals afterward.
| Method | Needs ownership of left side | Allocates | Best for |
|---|---|---|---|
| `a + &b` | Yes, `a` is moved | Only if the buffer grows | Short chains where the left `String` is no longer needed |
| `s += "x"` / `push_str` | No, needs `&mut` | Only if the buffer grows | Building a string step by step |
| `format!` | No, borrows all | Always, one new `String` | Mixed types and readable templates |
| `slice.join(sep)` | No | Once, exact size | Collections with a separator |
| `write!(buf, ...)` | No, needs `&mut` | Only if the buffer grows | Formatting many items into one buffer |
Common errors and gotchas
- Moved value.
let c = a + "x"; println!("{a}");fails with "borrow of moved value". If you needalater, useformat!("{a}x")or calla.clone() + "x". - Left side is a literal.
"x" + &sdoes not compile. Writeformat!("x{s}")or"x".to_string() + &s. - Repeated format in a loop.
s = format!("{s}{item}")copies the whole string on every pass, so the loop does quadratic work. Uses.push_str(item)orwrite!(s, "{item}"). - Trailing separator. Building a comma-separated list by pushing
itemand", "leaves a trailing,. Usingjoinavoids this. - Wrong
Writetrait. See the previous section. - Wrapping a single
+in&.&(a + "b")is legal but creates a temporaryStringthat is dropped at the end of the statement. Do not store the reference past that point.
Exercises
Exercise
Why does let s = String::from("a"); let t = s + "b"; println!("{s}"); fail to compile, and how do you change the code so that both s and the joined text are available afterward?
Show answer
The + operator takes s by value, so s is moved into the expression and cannot be used afterward. Use let t = format!("{s}b");, which only borrows s, or write let t = s.clone() + "b";.
Exercise
You have let names: Vec<String> = vec!["Ann".to_string(), "Bo".to_string()];. Write one expression that produces the String "Ann and Bo".
Show answer
names.join(" and "). join works on a slice of String values and places the separator only between elements.
Exercise
A loop runs 100000 times and does out = format!("{out}{n},");. Name the problem and give a fix that uses write!.
Show answer
Each iteration allocates a new String and copies all previous content, so the total work grows quadratically. Add use std::fmt::Write; and replace the line with write!(out, "{n},").unwrap();, which appends to the same buffer.