Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error in 8.2 (Futures/Spawn) Example Code #158

Open
iUnknwn opened this issue Oct 1, 2024 · 0 comments
Open

Error in 8.2 (Futures/Spawn) Example Code #158

iUnknwn opened this issue Oct 1, 2024 · 0 comments

Comments

@iUnknwn
Copy link

iUnknwn commented Oct 1, 2024

In the chapter on async spawn, there's example code for the function echoes:

use tokio::net::TcpListener;

pub async fn echo(listener: TcpListener) -> Result<(), anyhow::Error> {
    loop {
        let (mut socket, _) = listener.accept().await?;
        // Spawn a background task to handle the connection
        // thus allowing the main task to immediately start 
        // accepting new connections
        tokio::spawn(async move {
            let (mut reader, mut writer) = socket.split();
            tokio::io::copy(&mut reader, &mut writer).await?;
        });
    }
}

This code doesn't compile, due to the question mark operator on the final await, with the error:
"cannot use the ? operator in an async block that returns ()"

The solution handles this by simply unwrapping the operation, and that works.

Another option can be explicitly returning an Ok, setting the error type with the turbofish syntax.

pub async fn echo(listener: TcpListener) -> Result<(), anyhow::Error> {
    loop {
        let (mut socket, _) = listener.accept().await?;
        // Spawn a background task to handle the connection
        // thus allowing the main task to immediately start 
        // accepting new connections
        tokio::spawn(async move {
            let (mut reader, mut writer) = socket.split();
            tokio::io::copy(&mut reader, &mut writer).await?;

            Ok::<(), anyhow::Error>(())
        });
    }
}

This might be also worth calling out in the book, since it seems like there's no way to specify an async block's return type (at least not in the same way it can be done for a closure).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant