skip to content

A Rust `Thermostat::summary(&self)` calls `self.sensor.into_report()`, where `into_report` takes `self`, and fails with E0507: why, and how do you fix it?

level: seniorimportance: should knowfreq 40%

answer

  1. who owns self.sensor here
  2. a by-value receiver needs ownership
  3. cannot move out behind a reference
  4. borrowing and consuming twins
  5. as_, to_ and into_ names

basics

~20 s

A self receiver needs an owned Sensor, but summary only borrows the thermostat, and moving the field out would leave a hole. Fix it with a borrowing report(&self) on Sensor, a consuming into_summary(self) on Thermostat, or a deliberate clone.

solid answer

~40 s

`into_report(self)` takes ownership of its receiver, so `self.sensor.into_report()` tries to **move** `sensor` out of the thermostat. Inside `summary(&self)` the method only has a shared borrow, and the caller expects its thermostat back whole, so rustc reports E0507: "cannot move out of `self.sensor` which is behind a shared reference", noting that `into_report` takes ownership of the receiver. `&mut self` does not help; the message just says "mutable reference". The fixes follow what the caller needs: add a borrowing twin `fn report(&self) -> Report` that clones only what it must; make the outer method consuming, `fn into_summary(self)`, if the thermostat is finished; or clone the sensor when that cost is acceptable.

code

rust · 32 lines
rust
struct Sensor {
    label: String,
    last: f64,
}

struct Report {
    label: String,
    value: f64,
}

impl Sensor {
    fn into_report(self) -> Report {
        Report { label: self.label, value: self.last }
    }
}

struct Thermostat {
    sensor: Sensor,
    target: f64,
}

impl Thermostat {
    fn summary(&self) -> Report {
        self.sensor.into_report() // E0507: cannot move out of `self.sensor`
    }
}

fn main() {
    let t = Thermostat { sensor: Sensor { label: "lab".into(), last: 18.5 }, target: 20.0 };
    let r = t.summary();
    println!("{} {} {}", r.label, r.value, t.target);
}

go deeper

for a junior

Recognise that a method taking self moves the value it is called on, and that a field of a borrowed struct cannot be moved.

for a middle

Read E0507 and its note to find the consuming method, and explain why both &self and &mut self leave the field unmovable.

for a senior

Pick the fix from what the caller needs, a borrowing twin, a consuming outer method, an Option field or a clone, and explain each fix's cost.

for a principal

Treat E0507 as an API signal: types whose operations come in borrowing and consuming pairs spare callers both clones and awkward ownership.

## What the error is telling you Method calls are moves when the receiver is `self`. In ```rust fn summary(&self) -> Report { self.sensor.into_report() } ``` `into_report` is declared `fn into_report(self) -> Report`, so calling it needs an **owned** `Sensor`. The only `Sensor` available is the field `self.sensor`, and `summary` holds the thermostat through `&self`, a shared borrow. Moving the field out would leave the caller's `Thermostat` with an empty `sensor` slot that it would later read or drop. rustc refuses with **E0507**: - "cannot move out of `self.sensor` which is behind a shared reference" - a note: "`Sensor::into_report` takes ownership of the receiver `self`, which moves `self.sensor`" - if `Sensor` is not `Clone`, a note that implementing `Clone` would let you clone the value. Method lookup tries the by-value receiver type first, finds `into_report(self)`, and attempts the move; no `&` is inserted for you. Writing `(&self.sensor).into_report()` does not help either: lookup dereferences back to `Sensor` and you get E0507, "cannot move out of a shared reference". ## Why a hole cannot be allowed If rustc let the move happen, the thermostat's owner would still believe it holds a complete value: - It could read `sensor.label` after the call and see a `String` whose buffer now belongs to the report. - When the thermostat is dropped, it would drop that `String` a second time. Rust has no "moved-from" state for a field behind a reference, so the borrow checker rejects the move at compile time instead of tracking a hole at run time. ## The same error in other shapes The diagnosis is identical wherever a consuming method meets a borrowed place: | Code | Message | |---|---| | inside `fn summary(&mut self)` | "cannot move out of `self.sensor` which is behind a mutable reference" | | `for s in &mut sensors { s.into_label(); }` | "cannot move out of `*s` which is behind a mutable reference" | | `v[0].into_label()` with `v: &Vec<Sensor>` | "cannot move out of index of `Vec<Sensor>`" | An exclusive borrow is still a borrow: the caller gets the value back afterwards, so it must still be whole. ## Fixes, chosen by what the caller needs 1. **The caller keeps the thermostat: borrow instead of consume.** Give `Sensor` a borrowing twin, `fn report(&self) -> Report`, which clones only the `String` it needs, and call it from `summary(&self)`. This is the usual answer and the clone stays visible in one place. 2. **The thermostat is finished: consume it too.** Change the outer method to `fn into_summary(self) -> Report`. `self` is owned, so `self.sensor.into_report()` compiles and reuses the `String` with no clone. The receiver choice propagates: a consuming method can only be called from code that owns the value. 3. **The thermostat lives on without a sensor: take it out explicitly.** Store `sensor: Option<Sensor>` and, under `&mut self`, take the value and leave `None` behind (the `Option` methods are covered with `Option` and `Result`, and `mem::replace` with borrow-checker fixes). The empty state is now explicit in the type. 4. **Cloning is acceptable: clone the field.** With `#[derive(Clone)]` on `Sensor`, `self.sensor.clone().into_report()` compiles. It clones the whole sensor only to consume the copy, so it is the fallback, not the first reach. For a collection, iterating by value (`for s in sensors`) consumes the `Vec` and makes each element owned; which iterator form to use is covered with iteration. ## The design lesson: publish both receivers when both are needed The error usually means a type offers only the consuming form of an operation that callers also need in borrowing form. std's naming shows the convention: - `as_` for a cheap borrowed view, such as `String::as_str`; - `to_` for a conversion that builds a new owned value from a borrow, such as `str::to_owned`; - `into_` for a conversion that consumes `self`, such as `String::into_bytes`. Offering `report(&self)` beside `into_report(self)` lets each caller pick: borrowers pay for a clone, owners get the zero-copy path. ## What a strong answer covers - That `self` means move, and a field behind `&self` or `&mut self` cannot be moved. - That the fix depends on whether the outer value must survive, not on silencing the compiler. - That `clone()` works but hides a cost, and a borrowing twin is usually better.

  • Why does changing `summary` to take `&mut self` not fix the E0507?
    An exclusive borrow still returns the thermostat to its owner when the call ends, so the thermostat must be whole then. Moving `sensor` out would break that, so rustc reports E0507 again, now saying the field is behind a mutable reference. Only ownership, or replacing the field with another value, allows taking it out.
  • Why does method lookup not insert a borrow and call `into_report` on `&Sensor`?
    Lookup takes the first receiver type that has a method of that name, starting with the by-value type. `into_report(self)` matches `Sensor` itself, so the call is a move. No `into_report` takes `&Sensor`, so there is no borrowing method for lookup to fall back to.
  • How do you choose between a borrowing twin and making the outer method consuming?
    Ask whether the outer value is still needed. If callers keep using the thermostat, add `report(&self)` and accept a small clone. If a summary is the last thing done with it, `into_summary(self)` reuses the fields with no clone and makes the end of the value's life explicit.

  • Changing &self to &mut self allows moving a field out
  • rustc automatically borrows when a self method meets a reference
  • Calling clone() is always the right fix for E0507
  • (&self.sensor).into_report() passes the sensor by reference
  • E0507 means Sensor needs to implement Copy