我有一个函数,它接受一个泛型参数,从中得到它所需要的,然后返回一个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以获得单一混凝土类型外,还有什么方法可以解决这个问题?

推荐答案

我不认为你可以避免拳击,但至少你可以避免拳击future 本身:

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=()> {
    let read = if let Some(p) = p {
        Box::new(File::open(p).unwrap()) as Box<dyn Read>
    } else {
        Box::new(stdin())
    };
    f(read)
}

fn f<R: Read>(_: R) -> impl Future<Output=()> {
    fut()
}

async fn fut() {}

据我所知,问题不在于future ,而在于为参数构建不同的类型,并以某种方式涌入返回类型.这是有道理的,但事实并非如此.

Playground

Rust相关问答推荐

使用元组执行条件分支的正确方法

为什么复印是豆荚的一个重要特征?

如何使用 list 在Rust for Windows中编译?

防止cargo test 中的竞争条件

如何模拟/创建ReqData以测试Actix Web请求处理程序?

是否可以使用Rust宏来构建元组的项?

在本例中,为什么我不能一次多次borrow 可变变量?

如何修复数组中NewType导致的运行时开销

将一个泛型类型转换为另一个泛型类型

完全匹配包含大小写的整数范围(&Q;)

Rust wasm 中的 Closure::new 和 Closure::wrap 有什么区别

需要哪些编译器优化来优化此递归调用?

Rust中是否可以在不复制的情况下从另一个不可变向量创建不可变向量?

简单 TCP 服务器的连接由对等重置错误,mio 负载较小

类型判断模式匹配panic

为实现特征的所有类型实现显示

深度嵌套枚举的清洁匹配臂

如何从 many0 传播 Nom 失败上下文?

Rust 生命周期:不能在方法内重新borrow 可变字段

为什么我不能将元素写入 Rust 数组中移动的位置,但我可以在元组中完成