6 ms·
I had a hard time with closures when doing async programming. Is that something one should avoid?
by davidkunz 3y ago
I had a hard time with closures when doing async programming. Is that something one should avoid?
- techn00 3y agoI'd love to see a side by side comparison on how someone would use goroutines in Go vs tokio in Rust. Including with closures
- gdcbe 3y agoAsync programming in Rust can still be a bit awkward. They're working hard on it though. https://blog.rust-lang.org/inside-rust/2023/05/03/stabilizing-async-fn-in-trait.html https://blog.rust-lang.org/inside-rust/2023/05/03/stabilizin... We'll have Async traits in stable Rust after the summer (normally) and in 2024 they'll start working on supporting async closures :) So if all is well, you're experience should start to become more pleasant next year. For now your closures will either have to return a future (without use of `async` keyword) or you better avoid it for now. Then again, hadn't really had the need for async closures, but I did had a big need for Async traits, as implementing Traits with manual futures was so far a big pain in the ass, and sometimes still not optimal. So I for one, welcome async traits with open arms.
- masklinn 3y agoThe lack of asynchronous closures does make it awkward, as you often need to put an `async move` block inside the closure for things to work correctly, which means the closure becomes an FnOnce and you have to work around that using clones. It’s one of the worst corners of the ecosystem currently, and I’d very much recommend avoiding it.
- z3t4 3y agoAsync code is hard to reason about. Async closures is what I like most about JavaScript (JS) though. Because JS pass all variables by value they get frozen in time when passed to a function. This make async code easier to reason about, as all variables are immutable.
- davidkunz 3y agoIn JavaScript, primitive types are passed by value, objects are passed by reference. But you won't have data races since JavaScript code is executed in a single thread.
- shred45 3y agoI may be biased because I generally avoid closures entirely (I prefer the certainty over ownership and type signatures that traditional functions give), but I do my best to avoid closures when working with async in Rust. A lot of examples for frameworks will make use of async closures, and I typically convert those to functions as quickly as possible, which can be tricky the first time because of the elided types.