What is the concrete type of a future returned from `async fn`?

后端 未结 1 538
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 12:03

What type should I use for a vector that stores futures?

I tried to make multiple concurrent requests on the same URL and save all the futures into the vector to use

相关标签:
1条回答
  • 2020-12-11 12:38

    From the RFC:

    The return type of an async function is a unique anonymous type generated by the compiler, similar to the type of a closure. You can think of this type as being like an enum, with one variant for every "yield point" of the function - the beginning of it, the await expressions, and every return. Each variant stores the state that is needed to be stored to resume control from that yield point.

    When the function is called, this anonymous type is returned in its initial state, which contains all of the arguments to this function.

    You can't explicitly declare the concrete type of a future since it is an anonymous type. As an API user we only need to know that it implements std::futures::Future but this doesn't mean that we don't need a deeper knowledge of this anonymous type and it's implementation, it would be nice to have for grasping the concept.


    CLion determines the vector type as Vec<dyn Future<Output = ()>>

    This is a type hint, not the actual type, since compiler is not able to know the size of dyn Future<Output = ()>, it will not be compiled.


    Pin<Box<_>>-ing a Future to declare an explicit type might not be a good idea. In your case it's not needed because the concrete types returned from async fn are identical. Letting the compiler infer the type will just be fine.

    See also:

    • For various concrete return types : How can I put an async function into a map in Rust?
    • Static & Dynamic dispatch : Trait Objects
    0 讨论(0)
提交回复
热议问题