gpt4 book ai didi

rust - 接收通过引用传递的参数的异步函数向量

转载 作者:行者123 更新时间:2023-12-03 11:36:40 25 4
gpt4 key购买 nike

我想创建一个异步函数向量,但它只适用于 'static生命周期:

use std::future::Future;
use std::pin::Pin;

type BoxFuture<T> = Pin<Box<dyn Future<Output = T>>>;
type SimpleHandler = Box<dyn Fn(&u32, &u64) -> BoxFuture<Option<String>>>;

#[tokio::main]
async fn main() -> std::io::Result<()> {
let v: Vec<SimpleHandler> = vec![
Box::new(|a, b| Box::pin(handle_create_group(a, b))),
Box::new(|a, b| Box::pin(handle_drop_group(a, b))),
];

for f in &v {
println!("{:?}", (f)(&0, &0).await);
}

Ok(())
}

async fn handle_create_group(a: &u32, b: &u64) -> Option<String> {
Some("hello".into())
}

async fn handle_drop_group(a: &u32, b: &u64) -> Option<String> {
Some("world".into())
}
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter '_ in function call due to conflicting requirements
--> src/main.rs:10:34
|
10 | Box::new(|a, b| Box::pin(handle_create_group(a, b))),
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 10:18...
--> src/main.rs:10:18
|
10 | Box::new(|a, b| Box::pin(handle_create_group(a, b))),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:10:54
|
10 | Box::new(|a, b| Box::pin(handle_create_group(a, b))),
| ^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the expression is assignable
--> src/main.rs:10:25
|
10 | Box::new(|a, b| Box::pin(handle_create_group(a, b))),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
= note: expected `std::pin::Pin<std::boxed::Box<(dyn std::future::Future<Output = std::option::Option<std::string::String>> + 'static)>>`
found `std::pin::Pin<std::boxed::Box<dyn std::future::Future<Output = std::option::Option<std::string::String>>>>`
我可以将 future 的生命周期设置为绑定(bind)到参数生命周期吗?

最佳答案

我找到了解决方案:

type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
type SimpleHandler = Box<dyn for<'a> Fn(&'a u32, &'a u64) -> BoxFuture<'a, Option<String>>>;

关于rust - 接收通过引用传递的参数的异步函数向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64866474/

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