rust - 为什么我不能在需要可变引用时将异步函数作为字段传递?

标签 rust rust-tokio

我正在研究一个将异步函数作为字段的结构,但是当它采用可变引用时它不起作用。

这个有效:

#![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 bookasync 函数的返回值的生命周期受其参数生命周期的限制。您对 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/

相关文章:

rust - 是否可以在函数内有条件地编译代码块?

string - 如何将结构中的字符串与文字进行模式匹配

multithreading - 是否可以在当前线程中在 Tokio 的当前线程上生成工作?

asynchronous - 为什么在使用带有 std::sync::Mutex 的 Tokio 时会出现死锁?

rust - 跨异步闭包共享数据结构

rust - 可中止 : Dangling Futures?

rust - 存储任何 JoinHandle<> 变体

rust - 如何在 CLI 应用程序中处理 "./"、 "~/"和相关参数

rust - 如何使启用的两个功能导致 Rust 中的冲突?

reflection - 运行时反射能做什么编译时不能做的事情?