In Rust, why does a retry helper that calls its `on_success: G` callback, bounded by `G: FnOnce()`, inside its loop fail with E0382, and how do you fix it?
answer
- call_once takes self
- the next iteration is another path
- return right after the call
- Option plus take for stored callbacks
basics
~20 sCalling an FnOnce moves it, and the loop could reach that call again, so rustc reports use of a moved value. Return or break right after the call, call it once after the loop, or hold it in an Option and take() it.
solid answer
~50 s`FnOnce::call_once` takes `self`, so `on_success()` moves `on_success` just as passing it to a by-value function would. Inside a `for` loop, the borrow checker sees a path from that call back to the same call on the next iteration, and reports E0382, "`on_success` moved due to this call, in previous iteration of loop", with the note "`FnOnce` closures can only be called once". The check is flow-sensitive, so the fix is to make the second call impossible: `return` or `break` immediately after calling, or record success and call once after the loop. When the callback lives in a struct field, store it as `Option<Box<dyn FnOnce(u32)>>` and call `self.on_done.take()`, which moves it out and leaves `None`, because moving out of a field behind `&mut self` is E0507. Widening the bound to `FnMut` also compiles but rejects callers whose callback consumes a capture.
code
rust · 29 linesstruct Upload {
on_done: Option<Box<dyn FnOnce(u32)>>,
}
impl Upload {
fn finish(&mut self, bytes: u32) {
// take() leaves None behind, so a second finish() is a no-op
if let Some(callback) = self.on_done.take() {
callback(bytes); // Box<dyn FnOnce> is callable by value
}
}
}
fn retry_then<F: FnMut() -> bool, G: FnOnce()>(attempts: u32, mut op: F, on_success: G) {
for _ in 0..attempts {
if op() {
on_success(); // moved here, and the loop is left at once
return;
}
}
}
fn main() {
let receipt = String::from("upload-42");
let mut up = Upload { on_done: Some(Box::new(move |n| println!("{receipt}: {n} bytes"))) };
up.finish(1024);
up.finish(2048);
retry_then(3, || true, || println!("committed"));
}go deeper
Recall that calling an FnOnce consumes it, so the compiler rejects any path that could call it a second time.
Explain the E0382 note about the previous iteration, and fix it by returning after the call or calling once after the loop.
Store pending callbacks as Option<Box<dyn FnOnce>> and take() them, and push back on widening a bound to FnMut when callers rely on consuming closures.
Model one-shot completion explicitly in long-lived types: a taken Option makes a repeated finish a no-op by design rather than a latent double call.
## Why calling an FnOnce moves it The call traits differ in their receiver. `FnOnce::call_once` takes `self` by value, so `on_success()` on a value known only to be `FnOnce` moves it into the call, exactly like `drop(on_success)` would. Std's doc comment says it plainly: "if the only thing known about a type is that it implements `FnOnce`, it can only be called once." A generic `G: FnOnce()` is exactly that case: the helper knows nothing else about `G`, so even if the caller passed an `Fn` closure, the helper may only call it once. ## What the borrow checker sees in a loop The borrow checker does not count iterations; it follows the control-flow graph. A `for` loop body has an edge from its end back to its start, so a call inside the body can be reached again after it has already run once. rustc 1.99 reports: - **E0382**, "use of moved value: `on_success`"; - "`on_success` moved due to this call, in previous iteration of loop", with the loop marked "inside of this loop"; - a note, "`FnOnce` closures can only be called once", pointing at the `G: FnOnce()` bound. The same flow-sensitivity works in your favour. If the call is followed by `return` or `break`, no path from the call reaches it again, and the helper compiles unchanged. The error is about a path that exists, not about the loop keyword. ## The fixes | Fix | When it fits | What it costs | |---|---|---| | `return` or `break` right after the call | the callback marks the end of the work | nothing; the code says what it means | | record success, call once after the loop | cleanup must run after other loop work | a flag or a `match` on the result | | `Option<G>` and `take()` | the call site sits in a loop or is reached more than once | an `Option` check at run time | | widen the bound to `FnMut` | the callback is genuinely meant to run per success | callers can no longer pass consuming closures | The last row is a trap. `FnMut` accepts fewer closures than `FnOnce`: a callback that sends a captured `String` into a channel, or returns an owned receipt, is `FnOnce` only and would be rejected, with E0525 when the caller bound it to a variable first or E0507 when it is written inline in the call. Change the bound only when repeated calls are the intended behaviour. ## Stored once-callbacks When the callback is kept in a struct, for example an upload that notifies its caller when it finishes, the field is usually `Option<Box<dyn FnOnce(u32)>>`. 1. The `Option` records whether the callback is still pending. 2. `self.on_done.take()` moves the box out and leaves `None` behind, so a method that only has `&mut self` can still take ownership. Matching `if let Some(cb) = self.on_done` instead is **E0507**, "cannot move out of `self.on_done` as enum variant `Some` which is behind a mutable reference". 3. The box is then called by value. Std implements `FnOnce` for `Box<F>` where `F: FnOnce + ?Sized`, so `Box<dyn FnOnce(u32)>` is callable directly. 4. A second `finish()` finds `None` and does nothing, which turns "called twice" from a compile error into a defined no-op. Calling through a reference does not work: `self.on_done.as_ref().unwrap()(n)` is E0507 again, because an `FnOnce` call must own the box. ## Related facts worth knowing - A closure whose captures are all `Copy`, and none borrowed mutably, is itself `Copy`, so it can be called many times even after being moved; that does not help a helper that only knows `G: FnOnce()`. - `Option::map`, `Option::unwrap_or_else` and `thread::spawn` take `FnOnce` for the same reason this callback does: they call it once. ## Mistakes to avoid - Assuming `FnOnce` means "once per iteration" or "once per call of the helper". - Fixing E0382 by cloning the callback, which most closures do not support. - Widening `FnOnce` to `FnMut` or `Fn` to silence the error, which narrows what callers can pass.
- Why does adding `return;` right after `on_success()` make the helper compile?Because the borrow checker is flow-sensitive. After `return`, no path leads from the call back to the top of the loop, so there is no later use of the moved value. The bound and the callers stay unchanged; only the impossible second call is gone.
- Why does `if let Some(cb) = self.on_done { cb(n) }` fail in a `&mut self` method, and what replaces it?Matching the field by value would move the `Box<dyn FnOnce(u32)>` out of a place behind a mutable reference, which is E0507. `self.on_done.take()` swaps `None` in and hands you the owned box, which you then call by value.
- FnOnce means the callback runs once per loop iteration.
- Any call to an FnOnce inside a loop body is always an error.
- Box<dyn FnOnce()> cannot be called; it needs an unsized-value feature.
- Tightening the bound to Fn is the proper fix for E0382 on an FnOnce.
- A stored FnOnce can be called through a shared reference.