Hacker News new | past | comments | ask | show | jobs | submit login

> Haven't done too much async Rust yet but I don't think it solved this issue from what I've seen.

In Rust an async function is really just a const fn that synchronously only constructs and returns a state machine struct that implements the Future trait.

So

async fn foo(x: i32) { }

essentially desugars to

const fn foo(x: i32) -> FooFuture { FooFuture { x } }

struct FooFuture { x: i32 } // technically it's an enum modelling the state machine

impl Future for FooFuture { ... }

You have to explicitly spawn that onto a runtime or await it (i.e. combine it into the state machine that your code is already in). So that's actually really cool about how Rust handles async; that an async fn really isn't doing any magic, it just constructs a state machine and never interacts (or spawns) with a runtime at all, so it never starts running in the background, you are always in full control. And by throwing the future away, you are essentially cancelling it, there's no need to interact with any runtime either.




It's not const (const fn has a very specfic meaning in Rust), but other than that you're correct.


It is "const enough", as in, there is nothing preventing it from being called at compile time, in fact with nightly features (and no changes to the async fn), you can call it at compile time just fine. I also put const fn there to emphasize that it really can't do all that much beside constructing the state machine.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: