use futures::{future, Future};
use futures::future::{FutureExt, Ready};
use std::result::Result;
use std::error::Error;
// 返回 impl Future 的三种写法
async fn f() -> Result<usize, Box<dyn Error>> {
if false {
let a: Ready<Result<usize, Box<dyn Error>>> = futures::future::ok(1);
let b = a.map(|x| Ok(x.unwrap() + 1));
b.await
} else if true {
async{1}.map(|x|Ok(x+1)).await
} else {
let a = async {1};
let b = a.map(|x|Ok(x+1));
b.await
// then() 的使用:
// b.then(|x:Result<usize, Box<dyn Error>>| async {Ok(x.unwrap()+1)}).await
}
}
fn main() {
let a = f();
let c = futures::executor::block_on(a);
println!("{}", c.unwrap());
}
自动推导的类型如截图:
来源:oschina
链接:https://my.oschina.net/ooxxx/blog/4299204