Sphere
Log in Join
☆ 13

why does my async fn hold a borrow across await

I have an async function that takes &mut Vec<u8>, pushes some bytes, awaits a socket write, then pushes more bytes. I keep getting E0502 about a second mutable borrow even though the pushes are in separate statements. It feels like the compiler thinks the whole function holds the borrow for its entire duration. What's actually going on? Happy to share more detail if it helps.

⚑ Report

4 replies

☆ 0
L lastdbg ·2026-10-12#1

That's basically right. An async fn desugars to a state machine that captures its arguments, so the &mut Vec<u8> is a field of the future and lives as long as the future, including across every await point. From the borrow checker's perspective the borrow spans the whole async call.

⚑ Report
☆ 0
R route ·2026-10-17#2

So even though I only touch the vec before and after the await, the borrow covers the await in between? That's brutal. Does that mean I can't use any other reference to that vec while the async fn is pending?

⚑ Report
☆ 0
L loot ·2026-10-20#3

Correct. If you need to release the borrow across the await, restructure so the async part doesn't capture the vec. E.g. clone the bytes you need into an owned buffer, await the write, then borrow again afterward. Or pass the vec only to the small synchronous helper that does the pushes.

⚑ Report
☆ 0
C cardboard ·2026-10-24#4

Made a small owned buffer for the socket write and only borrow the vec in the synchronous push steps. The mental model that helped: an async fn owns its arguments for the lifetime of the returned future. Once I stopped thinking of it as a regular function, the borrow errors made sense.

⚑ Report
Log in to reply.