我有一個函式,它接受一個泛型引數,從中獲取它需要的東西,然后回傳一個未來。未來實際上并不存盤通用資料,它是完全單態的。
為方便起見,我想使用 anasync fn來創建未來,我知道這需要回傳一個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 在條件中嚇壞了,因為呼叫方絕對相信兩個分支之間的未來一定會有所不同:
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`)
除了拳擊未來或手動滾動fut以最終得到單一的混凝土型別之外,有沒有辦法解決這個問題?
uj5u.com熱心網友回復:
我不認為你可以避免拳擊,但至少你可以避免拳擊未來本身:
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() {}
據我了解,問題不在于未來,而實際上是為引數構建不同的型別,并以某種方式涌入回傳型別。這是有道理的,但它不會。
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/482083.html
上一篇:如何使用Anime.js正確地將svg變形為另一個svg?
下一篇:更改引數引數涉及的泛型
