Rust async closures

러스트 비동기 클로저

An async closure can borrow its captured values across the future it returns.

···
html
<div class="v"><header><b>ASYNC CLOSURE BORROW</b><span id="state"></span></header><main><div class="life"><div class="capture">CAPTURE <b>vec</b></div><div class="future" id="future">FUTURE <b>await</b></div><div class="line" id="line"></div></div><div class="borrow" id="borrow"></div></main><footer>the returned future may borrow captures</footer></div>
css
.v{width:min(92vw,660px);height:min(86vh,310px);box-sizing:border-box;padding:clamp(9px,2.5vmin,18px);border:1px solid var(--line);border-radius:14px;background:var(--surface);display:flex;flex-direction:column;gap:7px;color:var(--fg);font:500 clamp(15px,3.2vmin,17px)/1.25 var(--font-sans, sans-serif)}.v header,.v footer{display:flex;justify-content:space-between;align-items:center;gap:8px;white-space:nowrap}.v header b{color:var(--accent);font-size:.9em}.v header span,.v footer{color:var(--muted);font-size:.82em}.v main{flex:1;min-height:0;position:relative;overflow:hidden}.v .mono{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}.v .active{background:var(--accent)!important;color:var(--bg)!important;border-color:var(--accent)!important}.v .muted{opacity:.28} .life{height:69%;display:flex;align-items:center;justify-content:center;gap:7px;position:relative}.capture,.future{width:42%;box-sizing:border-box;border:1px solid var(--line);border-radius:6px;padding:9px 4px;text-align:center;font:600 clamp(12px,2.6vmin,16px) var(--font-sans, sans-serif)}.capture b,.future b{display:block;color:var(--accent)}.line{position:absolute;left:27%;right:27%;height:3px;background:var(--accent);bottom:15%;transition:opacity .25s}.borrow{text-align:center;color:var(--accent);font:600 clamp(12px,2.7vmin,16px) var(--font-sans, sans-serif)}
js
let n=0;const labels=["capture → future","borrow survives await","future done → borrow ends"];function draw(){document.getElementById("borrow").textContent=labels[n];document.getElementById("future").style.borderColor=n===2?"var(--line)":"var(--accent)";document.getElementById("line").style.opacity=n===2?".2":"1";document.getElementById("state").textContent="phase "+(n+1);n=(n+1)%3}draw();setInterval(draw,1150)

Rust 1.85 stabilized async || closures and the AsyncFn family of traits. The closure captures local values, creates a future containing await, and that future may borrow from the captures.

The older || async {} form could not express some of these borrows. The borrow remains tied to the future lifetime, so callers must respect the ownership rules while that future is alive.

When to use

Use it for async callbacks that access captured state across an await.

Open as page ↗