我正在研究一个将异步函数作为字段的结构,但是当它采用可变引用时它不起作用。
这个有效:
#![allow(dead_code)]
pub struct TestStruct;
struct TestStruct2<F>
where
F: std::future::Future<Output = ()>,
{
foo: fn(TestStruct) -> F,
}
async fn foo(_x: TestStruct) {}
#[tokio::main]
async fn main() {
let _s = TestStruct2 { foo };
}
这不起作用:
#![allow(dead_code)]
pub struct TestStruct;
struct TestStruct2<F>
where
F: std::future::Future<Output = ()>,
{
foo: fn(&mut TestStruct) -> F,
}
async fn foo(_x: &mut TestStruct) {}
#[tokio::main]
async fn main() {
let _s = TestStruct2 { foo }; //error here
}
错误:
mismatched types
expected fn pointer `for<'r> fn(&'r mut TestStruct) -> _`
found fn item `for<'r> fn(&'r mut TestStruct) -> impl std::future::Future<Output = ()> {foo}`
有人可以向我解释为什么会发生这种情况以及我能做些什么吗?
最佳答案
问题不在于mut
,而是引用及其生命周期。根据the Asynchronous Programming in Rust book ,async
函数的返回值的生命周期受其参数生命周期的限制。您对 TestStruct2::foo
的定义不接受这一点。要解决此问题,您可以将此生命周期显式添加到 F
:
struct TestStruct2<'a, F>
where
F: std::future::Future<Output = ()> + 'a,
{
foo: fn(&'a mut TestStruct) -> F,
}
关于rust - 为什么我不能在需要可变引用时将异步函数作为字段传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74049017/