You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

结构体中存储泛型异步回调的生命周期问题

Rust生命周期冲突:存储带trait约束的泛型异步回调指针问题

我尝试创建一个存储带trait约束的泛型异步回调指针的对象,但受限于生命周期冲突,即便遵循编译器提示也难以解决。调用存储回调的结构体方法时,编译器认为self的生命周期短于回调的生命周期,报错如下:

17 | impl<'a, 'b, T> ModalActionData<'a, 'b, T>
   |          -- lifetime `'b` defined here
...
36 |     pub async fn call(&mut self) -> CallbackReturnType {
   |                       - let's call the lifetime of this reference `'1`
37 |         (self.callback)(self.actionable, &mut self.data_sender).await
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ argument requires that `'1` must outlive `'b`

ModalActionData结构体定义:

pub struct ModalActionData<'a, 'b, T>
where
    T: ModalActionable,
    'a: 'b,
{
    pub action: String,
    pub actionable: &'a T,
    pub callback: Box<ModalActionCallback<'a, 'b, T>>,
    pub data_sender: DummyDataSender<String>,
}

ModalActionCallback相关类型定义:

pub type CallbackReturnType = Result<(), ()>;
pub type AsyncCallbackReturnType<'a> = Pin<Box<dyn Future<Output = CallbackReturnType> + 'a>>;
pub type ModalActionCallback<'a, 'b, T> =
    fn(&'a T, &'b mut DummyDataSender<String>) -> AsyncCallbackReturnType<'b>;

我尝试过调整生命周期、使用Pin<Box<...>>、添加'static生命周期、增减生命周期约束等方法,均未解决问题。

内容的提问来源于stack exchange,提问作者Quessours

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:52:48