如何使用 rust async_trait generic to a lifetime parameter?

How to use rust async_trait generic to a lifetime parameter?

我正在尝试创建一个 async_trait,其中某些实现对于具有生命周期参数的类型是通用的:

use async_trait::async_trait;

struct MyLifetimeType<'a> {
  s: &'a mut String,
}

#[async_trait]
trait MyTrait<T> {
  async fn handle(t: T);
}

struct MyImpl;

#[async_trait]
impl<'a> MyTrait<MyLifetimeType<'a>> for MyImpl {
  async fn handle(t: MyLifetimeType<'a>) {
    t.s.push_str("hi");
  }
}

当我尝试编译它时,我得到

error[E0276]: impl has stricter requirements than trait
  --> ...
   |
18 |   async fn handle(t: T);
   |   ---------------------- definition of `handle` from trait
...
25 |   async fn handle(t: MyLifetimeType<'a>) {
   |   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ impl has extra requirement `'a: 'async_trait`

这个问题似乎与 async_trait 以某种方式在后台使用生命周期参数 'a 有关。当我去掉所有 asyncasync_trait 时,代码编译正常。如何避免此 extra requirement 错误?

有关更多上下文,解释为什么处理程序实现 MyTrait 可以对包含可变指针的结构进行操作:我有一个函数获取 RwLockReadGuards 和 RwLockWriteGuards for a耦合不同的锁,然后将内容传递给处理程序。对于写保护,我需要一些方法让处理程序改变内容,所以我传递了一个可变指针。

这是a known issue。作者建议在发生该错误时添加明确的生命周期限制:

use async_trait::async_trait;

struct MyLifetimeType<'a> {
  s: &'a mut String,
}

#[async_trait]
trait MyTrait<T> {
  async fn handle(&self, t: T) where T: 'async_trait;
}

struct MyImpl;

#[async_trait]
impl<'a> MyTrait<MyLifetimeType<'a>> for MyImpl {

  async fn handle(&self, t: MyLifetimeType<'a>) {
    t.s.push_str("hi");
  }
  
}