Sub topic 6
Joining text with +, format!, and join
This chapter assumes you know basic Rust syntax, ownership and borrowing, and how String differs from &str. You will learn three ways to combine text, and when each one fits.
The + operator moves its left side
The + operator on strings calls String::add, whose signature is fn add(self, other: &str) -> String. The left operand must be an owned String. It is moved into the call, and Rust reuses its buffer to hold the result. The right operand must be a &str.
fn main() {
let a = String::from("tic");
let b = String::from("tac");
let c = a + "-" + &b;
let d = format!("{c}-toe");
println!("{d}");
}Here &b is a &String. Deref coercion turns it into the &str that add expects. After this line, a is no longer usable because it was moved. b is still valid because it was only borrowed.
The chain a + "-" + &b is evaluated left to right. Each + consumes the String produced by the one before it, so no extra copies of the left side are made.
format! builds a new String
format! uses the same syntax as println!, but it returns a String instead of printing. It borrows all of its arguments, so nothing is moved.
fn main() {
let first = String::from("Ada");
let last = String::from("Lovelace");
let full = format!("{first} {last}");
println!("{full}");
println!("{first} and {last} are still usable");
}Use format! when you mix several pieces, include non-string values, or need to keep the originals. It also accepts format specifiers such as {:>8} for padding and {:.2} for decimals.
fn main() {
let item = "tea";
let price = 3.5;
let line = format!("{item:<6}|{price:>8.2}");
println!("{line}");
}format! always allocates a new String. That is fine for most code. In a hot loop, consider the approach in the next section.
Appending with write! and push_str
If you already have a String and want to add to it, avoid creating temporary strings. push_str appends a &str. For formatted pieces, the write! macro writes into the buffer directly. It needs the std::fmt::Write trait in scope.
use std::fmt::Write;
fn main() {
let mut out = String::new();
for i in 1..=3 {
write!(out, "item{i};").unwrap();
}
out.push_str("end");
println!("{out}");
}Writing to a String cannot fail, so unwrap() is safe here.
join and concat for collections
When the pieces live in a slice or vector, use join and concat. join inserts a separator between items. concat joins them with nothing in between.
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("/"));
}join works on [&str] and [String]. It computes the total length first and allocates once. That makes it cheaper and clearer than a loop of +.
Choosing a method
| Situation | Best choice |
|---|---|
| Append one piece to an existing `String` | `push_str` or `push` |
| Two or three pieces, and you no longer need the left one | `+` |
| Mixed types, or you must keep the originals | `format!` |
| Many formatted pieces into one buffer | `write!` |
| A slice of strings with a separator | `join` |
Common errors
- Using
+on two&strvalues. The compiler reports a type mismatch, because&strdoes not implementAdd. Start fromString::fromor useformat!. - Using a moved variable. After
let c = a + "x";, readingais a compile error. Cloneafirst, or useformat!. - Writing
a + bwithbas aString. The right side must be borrowed, so writea + &b. - Building a long string with repeated
+in a loop. Preferpush_str,write!, or collecting and callingjoin.
Exercise
Why does let s = String::from("a") + String::from("b"); fail to compile, and how do you fix it?
Show answer
The right operand of + must be a &str, but String::from("b") is an owned String. Borrow it with &, as in String::from("a") + &String::from("b"). Using a plain literal such as String::from("a") + "b" also works.
Exercise
You have let parts = vec![String::from("x"), String::from("y"), String::from("z")];. Write one expression that produces "x-y-z" and leaves parts usable afterward.
Show answer
parts.join("-"). The join method borrows the slice, so parts is still usable afterward.