Poperton
Poperton

Reputation: 1796

How to specify an output type for a Future/async block?

use tokio::runtime::Runtime;

// Create the runtime
let rt  = Runtime::new().unwrap();

// Execute the future, blocking the current thread until completion
let s = rt.block_on(async {
    println!("hello");
});

is it possible to specify an output type for a future block? On the code above, s: (), but I wanted to be Result<(), Error> so I can return some error from inside the block.

Upvotes: 0

Views: 868

Answers (1)

Steve Lau
Steve Lau

Reputation: 1043

I am not quite familiar with async rust, but as far as I know, the return type of an async fn or async block is impl Future<Output=TheRealReturnTypeOfFnBody>. Once blocked on, as you did rt.block_on(async block), the return type will become TheRealReturnTypeOfFnBody, therefore:

To make s have type Result<(), Error>, you have to implement it in the function body(i.e. make TheRealReturnTypeOfFnBody Result<(), Error>)

use tokio::runtime::Runtime;

fn main() {
    // Create the runtime
    let rt = Runtime::new().unwrap();

    // Execute the future, blocking the current thread until completion
    let s: () = rt.block_on(async {
        println!("hello");
    });

    let s_with_error_case: Result<(), &str> = rt.block_on(async {
        if false {
            Err("run into a trouble")
        } else {
            println!("erverything is fine");
            Ok(())
        }
    });

    if let Err(err_info) = s_with_error_case {
        eprintln!("{}", err_info);
    }
}

Upvotes: 1

Related Questions