skip to content

In Rust, why does `s1 + &s2` move `s1`, why can two `&str` values not be added, and when is `format!` better?

level: juniorimportance: should knowfreq 55%

answer

  1. is a method taking self
  2. Add<&str> is implemented for String
  3. an owned String on the left
  4. format! borrows every argument

basics

~20 s

+ on strings calls Add<&str> for String, whose add takes self by value and appends with push_str, so s1 is moved. Two &str values have no owned buffer to append into, giving E0369. format! borrows all its arguments and builds a new String.

solid answer

~40 s

std implements `Add<&str>` only for `String`: `add(mut self, other: &str) -> String` calls `self.push_str(other)` and returns `self`. So `s1 + &s2` consumes `s1`, reuses its buffer, and `&s2` is a `&String` that deref-coerces to `&str`; using `s1` afterwards is E0382. `a + b` on two `&str` values is E0369, "cannot add `&str` to `&str`", because there is no owned `String` on the left to grow; rustc suggests `a.to_owned() + b`. `s1 + s2` with an owned right side is E0308, expected `&str`. `+=` is `AddAssign<&str>` and behaves like `push_str`. Reach for `format!("{user}@{domain}")` when joining several pieces or mixing in non-string values: it borrows everything and moves nothing, at the cost of always allocating a new `String`.

code

rust · 16 lines
rust
fn main() {
    let user = String::from("ada");
    let domain = "example.org";

    let mut a = String::with_capacity(32);
    a.push_str(&user);
    a.push('@');
    a.push_str(domain);

    let b = user.clone() + "@" + domain; // consumes the clone
    let c = format!("{user}@{domain}"); // borrows both

    assert_eq!(a, b);
    assert_eq!(b, c);
    println!("{a} {user}");
}

go deeper

for a junior

Recall that s1 + &s2 moves s1, that the right side must be a &str, and that format! is the readable way to join several values.

for a middle

Explain Add<&str> for String taking self by value, deref coercion turning &String into &str, and which of E0382, E0369 and E0308 each mistake produces.

for a senior

In review, prefer push_str in loops, with_capacity when the size is known, and format! when inputs must stay usable; flag clone() + &x chains that copy needlessly.

for a principal

Treat string building as an allocation question in hot paths: decide where one reused buffer beats many short-lived Strings, and make that a measured team convention rather than folklore.

## The `+` operator is one trait impl Rust has no built-in string concatenation. The `+` operator calls the **`Add`** trait, and for `String` the standard library implements exactly one form of it, quoted here from its source: ```rust impl Add<&str> for String { type Output = String; fn add(mut self, other: &str) -> String { self.push_str(other); self } } ``` Three consequences follow, and interviewers probe each one. - **The left side is moved.** `add` takes `self` by value, so `let s = s1 + &s2;` consumes `s1`. Its heap buffer is reused and grown if needed, then returned as `s`. - **The right side is borrowed as `&str`.** `&s2` has type `&String`, and **deref coercion** turns it into `&str` because `String: Deref<Target = str>`. `s2` is still usable afterwards. - **Only `String + &str` exists** among the `String` and `&str` combinations. There is no impl for `&str + &str`, `String + String` or `&str + String`. ## The three compile errors | Code | rustc 1.99 reports | Why | |---|---|---| | `s1 + &s2;` then `println!("{s1}")` | E0382, borrow of moved value: `s1` | `add` took `s1` by value | | `a + b` with `a, b: &str` | E0369, cannot add `&str` to `&str` | no owned `String` on the left to append into | | `s1 + s2` with both `String` | E0308, mismatched types: expected `&str`, found `String` | the right operand must be `&str` | For E0369 rustc adds the note "string concatenation requires an owned `String` on the left" and suggests `a.to_owned() + b`. For E0308 it suggests borrowing: `s1 + &s2`. For E0382 it suggests `s1.clone() + &s2`, which works but copies the whole string first. ## The other ways to build a `String` 1. **`push_str(&str)`** appends a string slice in place; `push(char)` appends one character. Both need a `let mut` binding and reuse the existing buffer. 2. **`+=`** is `AddAssign<&str> for String` and does exactly what `push_str` does. 3. **`format!`** takes a format string and arguments, borrows them all, and returns a fresh `String`. Format specifiers such as width and precision belong to the formatting machinery, not to `String`. 4. **`concat` and `join`** on a slice or array of strings (`[a, b].concat()`, `parts.join(", ")`) build one `String` from many. ## Choosing between them | Situation | Good choice | Reason | |---|---|---| | appending in a loop | `push_str` or `push` | grows one buffer in place | | one owned string plus a suffix | `s + suffix` | reuses `s`'s buffer | | several pieces, some not strings | `format!` | readable, borrows everything | | a list joined by a separator | `join` | no manual separator logic | | you still need every input afterwards | `format!` | nothing is moved | A chain like `s1 + "-" + &s2 + "-" + &s3` compiles and reuses `s1`'s buffer, but it reads poorly and still moves `s1`. The Rust Book reaches for `format!("{s1}-{s2}-{s3}")` in exactly that case. When the final size is known, `String::with_capacity` before a series of `push_str` calls avoids repeated reallocation; how capacity grows is the same story as for `Vec<u8>`, which a `String` wraps. ## What does not change - Every one of these produces valid UTF-8, because each input already is; none of them needs a check. - `+` never allocates a second buffer for the result; it may reallocate the left operand's buffer to make room. - `format!` always allocates a new `String`, even when one argument is already an owned `String` you no longer need. ## Traps worth flagging in review 1. **`s1.clone() + &s2`** to keep `s1` usable copies all of `s1` first; `format!` or a `push_str` into a new buffer says the same thing more cheaply and more clearly. 2. **`out += &format!("{x},")` inside a loop** allocates a temporary `String` on every iteration only to copy it and drop it. Writing into `out` directly with the `write!` macro and the `std::fmt::Write` trait avoids the temporary; the details belong to the formatting machinery. 3. **Adding a `char`.** `s + 'x'` is E0308, because `+` wants a `&str`; use `s.push('x')`, or `s + "x"`. 4. **Building a path or a URL by hand.** Concatenating with `+` and `/` hides separator bugs; dedicated builders such as `PathBuf::push` exist for paths.

  • Why does `s1 + &s2` compile when `&s2` is a `&String`, not a `&str`?
    The function expects `&str`, and `String` implements `Deref<Target = str>`. At a coercion site such as a function argument, rustc applies deref coercion and turns `&String` into `&str` automatically. That is why the right operand needs the `&` but not an explicit `.as_str()`.
  • Is `s1 + &s2` slower than `format!("{s1}{s2}")`?
    Usually not. `+` appends into `s1`'s existing buffer, reallocating only if capacity runs out, while `format!` always allocates a new `String` and copies both inputs. The real reasons to prefer `format!` are readability with many pieces and keeping every input usable.
  • How do you append a single character to a `String`?
    Call `push(c)` with a `char`. `push_str` and `+` take a `&str`, so passing a `char` to them is a type error; `push` encodes the character as one to four UTF-8 bytes and appends them.

  • The + operator borrows both strings and leaves s1 usable.
  • Two &str values can be added with + because both are strings.
  • s1 + s2 works when both operands are owned Strings.
  • format! moves its String arguments into the result.
  • + always allocates a brand-new String for the result.