러스트 비동기 클로저

Rust async closures

async 클로저가 캡처한 값을 비동기 작업 동안 빌려 쓸 수 있습니다.

···
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는 async || 문법과 AsyncFn 계열 트레이트를 안정화했습니다. 클로저가 주변 값을 캡처하고 await를 포함한 작업을 만들 수 있으며, 반환된 future가 캡처한 값을 빌릴 수 있습니다.

기존의 || async {} 형태에서는 내부 future가 클로저의 캡처를 빌리는 경우를 표현하기 어려웠습니다. 빌림은 future의 수명과 연결되므로 호출자가 그 future를 유지하는 동안 소유권 규칙을 지켜야 합니다.

언제 쓰나

캡처한 상태를 await 전후에 쓰는 비동기 콜백을 만들 때 씁니다.

페이지로 열기 ↗