Search code examples
rustfuturerust-async-std

Is the return type of the connect() function of the async-std crate a type of Future?


The document of the function connect() says it would return a Future.

This method will create a new TCP socket and attempt to connect it to the addr provided. The returned future will be resolved once the stream has successfully connected, or it will return an error if one occurs.

And from its signature, pub async fn connect<A: ToSocketAddrs>(addrs: A) -> io::Result<TcpStream>, the return value is of type std::io::Result and can be used with the 'await' syntax, such as let mut socket = async_std::net::TcpStream::connect((host, port)).await?;.

But I can't find the Future trait implementation of the type std::io::Result. My questions are:

  1. Does the std::io::Result implement the Future trait?
  2. If it doesn't implement the trait, why can we still apply the 'await' syntax on it?

Solution

  • The async keyword in the function signature means the function returns a Future. These two function signatures have the same declared return type:

    async fn foo() -> T { ... }
    
    fn foo() -> impl Future<Output=T> { ... }
    

    You can apply this return type transformation to any function marked async.