我有一个函数,它接受一个泛型参数,从中得到它所需要的,然后返回一个future .future 实际上并不存储通用数据,它是完全单态的.
为了方便起见,我想使用async fn
创建future ,我理解这需要返回impl Future
作为async fn
返回不透明类型:https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c3b061d12a126dc30099ac3bd018c273
use std::io::{Read, stdin};
use std::fs::File;
use std::future::Future;
use std::path::Path;
fn caller(p: Option<&Path>) -> impl Future<Output=()> {
if let Some(p) = p {
f(File::open(p).unwrap())
} else {
f(stdin())
}
}
fn f<R: Read>(_: R) -> impl Future<Output=()> {
fut()
}
async fn fut() {}
然而,rustc在条件中发疯了,因为调用方完全相信这两个分支之间的future 一定会有所不同:
error[E0308]: `if` and `else` have incompatible types
--> src/lib.rs:10:9
|
7 | / if let Some(p) = p {
8 | | f(File::open(p).unwrap())
| | ------------------------- expected because of this
9 | | } else {
10 | | f(stdin())
| | ^^^^^^^^^^ expected struct `File`, found struct `Stdin`
11 | | }
| |_____- `if` and `else` have incompatible types
...
14 | fn f<R: Read>(_: R) -> impl Future<Output=()> {
| ---------------------- the found opaque type
|
= note: expected type `impl Future<Output = ()>` (struct `File`)
found opaque type `impl Future<Output = ()>` (struct `Stdin`)
除了拳击future 或手动滚动fut
以获得单一混凝土类型外,还有什么方法可以解决这个问题?