3 ms·
Exciting! I know this has been a long time coming, so congrats to everyone for finally landing it in stable. As a rust noob, small question based on the exampl
by losvedir 7y ago
Exciting! I know this has been a long time coming, so congrats to everyone for finally landing it in stable.
As a rust noob, small question based on the example given: Why does `another_function` have to be defined with `async fn`? Naively, I would expect that because it calls `future.await` on its own async call, that from the "outside" it doesn't seem like an async function at all. Or do you have to tag any function as async if it calls an async function, whether or not it returns a future?
- estebank 7y agoYou have to tag a function as async if interacts with anything async and doesn't create an executor itself. Executors have functionality that let you start an async fn/block in the currently instantiated executor and return immediately. Such a function wouldn't need to be marked async, IIUC. Note that marking a function as async is only syntactic sugar for a function that returns a future.
- Matthias247 7y agoEven if you don’t await anything async fns behave different. They will get compiled to a function which returns a Future. When you call the function - nothing happens. The body will only be executed when someone starts polling the Future. This will also have a big impact on all lifetimes - since they now get part of the returned Future type. Now would you tag something as async if not required? Likely not - it just makes things more complicated. One exception is when you expect you need to modify the body of the function in the Future to make use of await, and you want to maintain compatibility
- jkarneges 7y agoAn async function compiles down a function that returns an iterable-ish state machine thing (a Future), that needs to be stepped through. The await keyword indicates a yield point. It's kind of like how if you declare a Python function containing the yield keyword, then the function returns an iterable rather than simply executing top to bottom. In the same way that Python yield only makes sense from within an iterable, Rust's await keyword only makes sense inside of a Future. Outside of a Future, there'd be no concept of a yield. This is why the "outer" function must be declared async.