繁体   English   中英

如何将 rust async_trait 泛型用于生命周期参数?

[英]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可以对包含可变指针的结构进行操作:我有一个函数,它获取RwLockReadGuard s 和RwLockWriteGuard s 以获得几个不同的锁,然后将内容传递给处理程序。 对于写保护,我需要某种方式让处理程序改变内容,所以我传递了一个可变指针。

这是一个已知问题 作者建议在发生该错误时添加一个明确的生命周期界限:

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");
  }
  
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM