In Rust, why does `fn greet(name: String) -> impl Future<Output = usize> { async { name.len() } }` fail with E0373, and how does `async move` fix it?
answer
- captures like a closure
- inferred borrow of name
- the future outlives the function
- move the String into the future
basics
~20 sA plain async block infers captures like a closure, so it only borrows name, and the returned future would outlive the function that owns it. async move moves name into the future, which then owns it and can be returned.
solid answer
~40 sAn `async` block captures variables with the same inference as a closure: `name.len()` needs only `&String`, so the block borrows `name`. The block is returned from `greet`, but `name` is dropped when `greet` returns, so rustc reports E0373, "async block may outlive the current function, but it borrows `name`", and suggests `move`. `async move { name.len() }` moves every variable the block mentions into the future, so the `String` travels with it. Two caveats: if the variable is itself a reference (`let tag = &name;`), `move` moves only the reference and the borrow fails as E0597; and after the move the caller can no longer use `name` (E0382), so clone first when both need it. An `async fn` body already behaves like an `async move` block.
code
rust · 7 linesuse std::future::Future;
fn greet(name: String) -> impl Future<Output = usize> {
async { name.len() }
}
fn main() { let _ = greet(String::from("x")); }go deeper
Recall that an async block borrows by default like a closure, and that async move hands ownership of the variables to the future.
Explain closure-style capture inference, why a returned borrowing future triggers E0373, and how async move, clone-before-move and E0382 interact.
Spot the reference-moved-by-move trap that turns E0373 into E0597, and decide what to clone or Arc so a future owns exactly what it needs.
Set the habit for code that builds futures in loops or helpers: clone narrowly before async move rather than cloning whole structs or reaching for 'static data.
## Async blocks capture like closures An **`async` block** is an expression that evaluates to a future, a value of an anonymous type implementing `Future`. The Reference puts it directly: executing an async block is similar to executing a closure expression, and async blocks capture variables from their environment **using the same capture modes as closures**. For each variable the block mentions, rustc infers the weakest capture that the body needs: - `name.len()` only reads, so it captures `&name`; - `name.push('!')` mutates, so it captures `&mut name`; - `drop(name)` consumes, so it captures `name` by value. That inference is perfect for a future that is awaited on the spot. It is wrong for a future that **leaves the function**. ## Why E0373 fires in greet ```rust fn greet(name: String) -> impl Future<Output = usize> { async { name.len() } } ``` The block borrows `name`. `greet` returns the block, then drops `name` at its closing brace. The future would hold a reference to a dropped `String`, so rustc 1.99.1 refuses it: ```plaintext error[E0373]: async block may outlive the current function, but it borrows `name`, which is owned by the current function help: to force the async block to take ownership of `name` (and any other referenced variables), use the `move` keyword ``` E0373 is the same error code a borrowing closure gets when it escapes; with an async block the escaping value is the future. ## What async move changes `async move { name.len() }` **moves every referenced variable into the future**, whatever the body needs. The `String` now lives inside the future's state, and `greet` can return it. Consequences: 1. The future owns `name` and drops it when the future completes or is dropped. 2. A `Copy` value such as a `u32` is copied in, so the original stays usable. 3. A non-`Copy` value is gone from the enclosing scope; using it afterwards is **E0382**, "borrow of moved value". 4. A variable that is itself a reference is moved *as a reference*: the future still borrows the original data. ## Three traps after adding move | Code inside a function owning `name: String` | Result on rustc 1.99.1 | Fix | |---|---|---| | `let tag = &name; async move { tag.len() }`, returned | **E0597** `name` does not live long enough | move the `String` itself, or an owned clone | | `let f = async move { name.len() }; println!("{name}");` | **E0382** borrow of moved value | `let owned = name.clone();` and move `owned` | | `for n in &names { v.push(async move { n.len() }) }` with `names: Vec<String>` owned by the function, then `v` returned | **E0597** `names` does not live long enough | iterate by value (`for n in names`) or clone each item | The clone pattern is the everyday answer: clone (or `Arc::clone`) exactly the data the future needs, then let `async move` take the clone. ## Control flow inside an async block The Reference treats an async block as a **function boundary**, like a closure: - `return expr` inside the block completes **the future** with `expr`; it does not return from the enclosing function; - `expr?` propagates the error as the future's output, so the block's output type must be a `Result` or an `Option`; - `break` and `continue` cannot leave the block: `break` inside an `async` block is **E0267**. ## Where async fn fits An `async fn` body is defined in terms of an `async move` block that captures every parameter, so its parameters are always owned by its future; the question of `move` never arises for them. It arises when you write `async` blocks yourself: returning one from a function, storing one in a `Vec`, or passing one to a spawn function, which typically also demands `'static` and `Send`, covered with spawning.
- If `tag` is `&name` and you write `async move { tag.len() }`, why does returning the block still fail?`move` moves the variable the block mentions, and that variable is a `&String`, so the future owns a reference, not the `String`. When the function returns, `name` is dropped while the future still borrows it, and rustc 1.99.1 reports E0597, `name` does not live long enough. Mention `name` itself, or an owned clone, inside the block.
- Does `?` inside an `async` block return an error from the enclosing function?No. An async block is a function boundary: `?` and `return` complete the block's future with that value, so the error becomes the future's output. The block's output type must be a `Result` (or `Option`), and the enclosing function sees the error only when it awaits the future and handles that output.
- Why does an `async fn` never need the `move` keyword?Its body is defined as an `async move` block that captures every parameter, so the returned future already owns its arguments; a borrowed parameter such as `&str` is captured as a reference with its lifetime. `move` matters only for `async` blocks you write yourself.
- async move clones the String, so the original variable stays usable.
- A plain async block always takes ownership of the variables it uses.
- async move on a reference variable makes the future own the referenced data.
- E0373 here is fixed by adding + 'static to the returned impl Future.
- return inside an async block returns from the enclosing function.