skip to content

In Rust, what do `x` and `y` bind in `for (i, &(x, y)) in points.iter().enumerate()` over a `Vec<(f64, f64)>`, and what changes without the `&`?

level: middleimportance: should knowfreq 45%

answer

  1. what iter() actually yields
  2. a & pattern matches the reference
  3. default binding mode: move, ref, ref mut
  4. non-Copy element: E0507

basics

~10 s

iter() yields &(f64, f64), and the reference pattern &(x, y) matches that reference and dereferences it, so x and y are f64 copies. Without the &, the default binding mode makes them &f64 borrows.

solid answer

~40 s

`enumerate()` yields `(usize, &(f64, f64))`, so `i` is a `usize`. The **reference pattern** `&(x, y)` matches the `&` itself and destructures the tuple behind it; `x` and `y` bind by value, which copies, because `f64` is `Copy`. Drop the `&` and a tuple pattern meets a reference: rustc dereferences it for you and switches the **default binding mode** from move to `ref`, so `x` and `y` become `&f64` ("match ergonomics"). The choice matters for non-`Copy` data: over `Vec<(String, u32)>`, `&(name, score)` would move a `String` out of a shared reference and fails with E0507, while `(name, score)` binds `&String` and `&u32`. A reference pattern must also fit the item: over `iter_mut()` or `into_iter()` the same `&(x, y)` is E0308.

code

rust · 21 lines
rust
fn type_of<T>(_: &T) -> &'static str {
    std::any::type_name::<T>()
}

fn main() {
    let points: Vec<(f64, f64)> = vec![(0.0, 0.0), (3.0, 4.0)];

    // Reference pattern: the & is matched, x and y are f64 copies.
    for (i, &(x, y)) in points.iter().enumerate() {
        println!("{i}: {} {}", type_of(&x), type_of(&y));
    }
    // No & in the pattern: default binding mode `ref`, x and y are &f64.
    for (i, (x, y)) in points.iter().enumerate() {
        println!("{i}: {} {}", type_of(&x), type_of(&y));
    }
    // Non-Copy data: (name, score) borrows; &(name, score) would be E0507.
    let named: Vec<(String, u32)> = vec![("ana".into(), 7)];
    for (name, score) in named.iter() {
        println!("{} {}", type_of(&name), type_of(&score));
    }
}

go deeper

for a junior

Recall that iter() yields references and that a pattern can unpack a tuple inside a for loop.

for a middle

Explain the reference pattern versus the default binding mode, give the resulting types, and say why the & version is E0507 on a Vec<(String, u32)>.

for a senior

Read an unfamiliar loop header by first naming the item type, and predict E0507 or E0308 before compiling when someone changes iter() to iter_mut() or into_iter().

for a principal

No lead decision lives here; at most, a review preference for borrowing patterns over & patterns on non-Copy data so that a type change does not turn into a move.

## What the iterator hands the pattern A `for` loop binds each item through a pattern, exactly like `let`. To read the header, first work out the item type: - `points.iter()` over a `Vec<(f64, f64)>` yields **`&(f64, f64)`**, a shared reference to each element. - `.enumerate()` wraps each item with its index, so the loop sees **`(usize, &(f64, f64))`**. The outer tuple pattern `(i, ...)` takes that pair apart: `i` binds the `usize`, and the second element, a reference, is matched against `&(x, y)`. ## Reference patterns match the `&` itself A **reference pattern** is `&` (or `&mut`) followed by another pattern. The Rust Reference says reference patterns "dereference the pointers that are being matched". So `&(x, y)` matches the `&`, then matches the tuple behind it against `(x, y)`. Because the reference was written out explicitly, the **default binding mode** is still *move*, and `x` and `y` bind by value. For `f64`, which is `Copy`, that is a copy: `x` and `y` are plain `f64` values, independent of the vector. Reference patterns are always irrefutable, so they are legal in a `for` loop. ## Default binding modes ("match ergonomics") Now remove the `&`: `for (i, (x, y)) in points.iter().enumerate()`. A tuple pattern is being matched against a `&(f64, f64)`, a non-reference pattern meeting a reference. Rust handles this with **default binding modes**: 1. Matching starts in **move** mode. 2. When a non-reference pattern meets a `&T`, rustc dereferences automatically and switches the mode to **`ref`**; a `&mut T` switches it to **`ref mut`**, unless the mode is already `ref`. 3. If the dereferenced value is again a reference, the process repeats. 4. A binding with no explicit `ref`, `ref mut` or `mut` uses the current mode. So `x` and `y` are bound as if written `ref x` and `ref y`: they are **`&f64`**, borrowing into the vector. For arithmetic on `f64` this rarely shows (`x + y` works on two `&f64`), but the types differ, and a function expecting `f64` needs `*x`. | Loop header over `points.iter().enumerate()` | `x` and `y` are | Why | |---|---|---| | `for (i, &(x, y)) in ...` | `f64` | the `&` pattern consumed the reference; move mode copies | | `for (i, (x, y)) in ...` | `&f64` | default binding mode switched to `ref` | ## When the element is not `Copy` The two spellings stop being interchangeable once the element owns heap data. Over `named: Vec<(String, u32)>`: - `for (name, score) in named.iter()` compiles: binding mode `ref`, so `name: &String` and `score: &u32`. - `for &(name, score) in named.iter()` fails with **E0507**, "cannot move out of a shared reference": the `&` pattern put the mode back to move, and binding `name` by value would move a `String` out of a vector the loop only borrows. rustc suggests `&(ref name, score)`, which borrows `name` and copies `score`. The rule of thumb: write `&` in a pattern to copy small `Copy` values out of a reference; leave it out to borrow. ## The reference pattern must fit the item type A reference pattern is checked against the type it meets, so changing the iterator changes what compiles: - `points.iter_mut()` yields `&mut (f64, f64)`. `&(x, y)` fails with **E0308**, "types differ in mutability"; write `&mut (x, y)` to copy, or `(x, y)` to get `&mut f64` through the `ref mut` mode. - `points.into_iter()` yields owned `(f64, f64)`. `&(x, y)` fails with **E0308**, "expected `(f64, f64)`, found `&_`"; write `(x, y)`. What `iter`, `iter_mut` and `into_iter` yield is covered with iteration; the point here is that the pattern must agree with it. ## The same rules in closures and `let` Nothing here is special to `for`. Closure parameters and `let` statements bind through the same patterns, with the same binding modes: - `points.iter().map(|&(x, y)| x * y).sum::<f64>()` copies each pair out through a reference pattern, so the closure works on plain `f64` values. - `points.iter().map(|(x, y)| x * y)` also compiles, because `x` and `y` are `&f64` and multiplication is implemented for references to floats, but the closure now borrows. - `let (name, n) = &pair;` on a `(String, u32)` binds `name: &String` and `n: &u32`; writing `let &(name, n) = &pair;` instead is E0507 for the same reason as the loop. So the habit transfers: look at what is being matched, a value or a reference, before reading the bindings. ## Interview checklist - Name the item type first; the pattern only makes sense against it. - Say "reference pattern" for `&(x, y)` and "default binding mode" for the elided case. - Know that `&` in a pattern copies or moves, and that E0507 is the price on non-`Copy` data.

  • Over `points.iter_mut()`, which loop header lets the body write `*x += 1.0`?
    `for (x, y) in points.iter_mut()`. The tuple pattern meets a `&mut (f64, f64)`, the default binding mode becomes `ref mut`, and `x` and `y` are `&mut f64`. `&(x, y)` is E0308 because the mutability differs, and `&mut (x, y)` copies the values out as `f64`, so `*x` is E0614, type `f64` cannot be dereferenced, and the vector is untouched.
  • What does `&(ref name, score)` do that neither `&(name, score)` nor `(name, score)` does?
    It mixes modes. The explicit `&` keeps the default mode at move, so `score` is copied as a `u32`, while `ref name` asks for a borrow, so `name` is a `&String` and nothing moves. `(name, score)` borrows both; `&(name, score)` tries to move `name` and fails with E0507.

  • `&(x, y)` in a pattern takes a reference to the tuple, like `&` in an expression.
  • `x` and `y` are `f64` with or without the `&`; it is only style.
  • `for &(name, score) in v.iter()` works for any element type.
  • The `&` pattern works the same over `iter()`, `iter_mut()` and `into_iter()`.
  • Match ergonomics means patterns can move out of borrowed data.