async trait中函数与实现的生命周期不匹配问题求助
问题原因与解决方案
问题根源
async_trait宏会对 trait 中的异步方法进行代码展开,自动添加必要的生命周期参数和约束;但你的impl块未使用该宏,导致实现的方法生命周期签名与 trait 展开后的签名不匹配,触发了E0195错误。
修复方案
在实现 trait 的impl块上方同样添加#[async_trait]宏即可解决问题。
修复后的完整代码
use std::time::Duration; use async_trait::async_trait; #[derive(Debug)] struct Resources(Vec<usize>); #[async_trait] pub trait System { async fn run(&mut self, res: &Resources, t: Duration, dt: Duration); } #[async_trait] impl System for () { async fn run(&mut self, _: &Resources, _: Duration, _: Duration) {} }
补充说明
当给 trait 加上#[async_trait]时,宏会将异步方法转换为返回Pin<Box<dyn Future<Output = ...> + Send + 'async_trait>>(默认行为)的方法,并为参数的生命周期添加适配的约束。如果impl块不使用该宏,编译器识别到的方法签名就会和 trait 实际展开后的签名不一致,最终导致生命周期不匹配的报错。
内容的提问来源于stack exchange,提问作者E Y
相关产品推荐
相关产品推荐

