我正在嘗試使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有關。當我擺脫所有asyncand 時async_trait,代碼編譯得很好。我怎樣才能避免這個extra requirement錯誤?
有關更多背景關系,要解釋為什么要實作MyTrait可以對包含可變指標的結構進行操作的處理程式:我有一個函式,它為幾個不同的鎖獲取RwLockReadGuards 和RwLockWriteGuards,然后將內容傳遞給處理程式。對于寫保護,我需要某種方式讓處理程式改變內容,所以我傳遞了一個可變指標。
uj5u.com熱心網友回復:
這是一個已知問題。作者建議在發生該錯誤時添加一個明確的生命周期界限:
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");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/318771.html
