gpt4 book ai didi

Rust:预期类型 [X],但发现类型 [X]

转载 作者:行者123 更新时间:2023-12-05 05:39:32 25 4
gpt4 key购买 nike

当 Rust 提示两个相同的类型不匹配时,这是什么意思?

以下错误似乎是在比较类型...

<for<'_> fn(&u32) -> impl futures::Future<Output = u32> {f} as FnOnce<(&u32,)>>::Output

...对它自己。

error[E0308]: mismatched types
--> src/main.rs:31:18
|
31 | let output = map(f, input);
| ^^^ lifetime mismatch
|
= note: expected associated type `<for<'_> fn(&u32) -> impl futures::Future<Output = u32> {f} as FnOnce<(&u32,)>>::Output`
found associated type `<for<'_> fn(&u32) -> impl futures::Future<Output = u32> {f} as FnOnce<(&u32,)>>::Output`
= note: the required lifetime does not necessarily outlive the empty lifetime
note: the lifetime requirement is introduced here
--> src/main.rs:6:39
|
6 | pub fn map<U, V, W>(f: impl Fn(&U) -> W, items: Vec<U>) -> impl futures::Stream<Item = V>
| ^

我已将其简化为以下最小示例:

use futures::stream::{FuturesUnordered, StreamExt};
use async_stream::stream;

pub fn map<U, V, W>(f: impl Fn(&U) -> W, items: Vec<U>) -> impl futures::Stream<Item = V>
where V: Send, W: futures::Future<Output = V> + Send
{
stream! {
let mut futures = FuturesUnordered::new();
let mut i = 2;
if 2 <= items.len() {
futures.push(tokio::spawn(f(&items[0])));
futures.push(tokio::spawn(f(&items[1])));
while let Some(result) = futures.next().await {
let y = result.unwrap();
yield y;
futures.push(tokio::spawn(f(&items[i])));
i += 1
}
}
}
}

#[tokio::main]
async fn main() {
async fn f(x: &u32) -> u32 {
x + 1
}
let input = vec![1, 2, 3];
let output = map(f, input);
futures::pin_mut!(output);
while let Some(x) = output.next().await {
println!("{:?}", x);
}
}

最佳答案

这意味着它们不相等,只是这样显示,rustc 省略了一些重要的细节。

在这种情况下,省略的重要信息是一辈子的,我来注释一下:

expected associated type `<for<'_> fn(&u32) -> impl futures::Future<Output = u32> {f} as FnOnce<(&u32,)>>::Output`
found associated type `<for<'_> fn(&u32) -> impl futures::Future<Output = u32> + '_ {f} as FnOnce<(&u32,)>>::Output + '_`

或者用名字,

expected associated type `<for<'a> fn(&'a u32) -> impl futures::Future<Output = u32> {f} as FnOnce<(&'a u32,)>>::Output`
found associated type `<for<'a> fn(&'a u32) -> impl futures::Future<Output = u32> + 'a {f} as FnOnce<(&'a u32,)>>::Output + 'a`

这是因为 async fn f() 被脱糖成:

fn f<'a>(x: &'a u32) -> impl futures::Future<Output = u32> + 'a {
async move { x + 1 }
}

也就是说,最终的 future 取决于参数的生命周期(因为它捕获了它)。然而,map() 期望它不会,因为它是一个独立的通用参数 (W)。

有关更多和潜在的解决方案,请参阅 Lifetime of a reference passed to async callback .

关于Rust:预期类型 [X],但发现类型 [X],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72651369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com