簡體   English   中英

在 Rust 中,如何使用 self 制作 trait 的 vec?

[英]In Rust, how to make an vec of trait with self?

只是想知道如何將帶有 self 的 trait放入 vec 中? 我認為這應該是一個常見問題,但我從未搜索過答案......

這是代碼:

use tokio::time::{delay_for, Duration};

#[async_trait::async_trait]
trait Interface: Default + Sized {
    async fn update(&mut self) -> bool where Self: Sized;
}

struct Adder {
    pub state: i32,
}

impl Default for Adder {
    fn default() -> Self {
        Self { state: 0 }
    }
}

#[async_trait::async_trait]
impl Interface for Adder {
    async fn update(&mut self) -> bool {
        delay_for(Duration::from_millis(100)).await;
        self.state = self.state + 1;
        println!("Inc state to: {}", self.state);
        return true;
    }
}

struct Suber {
    pub state: i32,
}


impl Default for Suber {
    fn default() -> Self {
        Self { state: 0 }
    }
}


#[async_trait::async_trait]
impl Interface for Suber {
    async fn update(&mut self) -> bool {
        delay_for(Duration::from_millis(100)).await;
        self.state = self.state - 1;
        println!("Dec state to: {}", self.state);
        return true;
    }
}

fn main() {
    let updaters: Vec<Box<dyn Interface>> = vec![Box::new(Adder::default()), Box::new(Suber::default())];
    for mut u in updaters {
        u.update();
    }
}

但我會得到錯誤:

error[E0038]: the trait `Interface` cannot be made into an object
  --> src/main.rs:51:19
   |
4  | trait Interface: Default + Sized {
   |       ---------  -------   ----- ...because it requires `Self: Sized`
   |       |          |
   |       |          ...because it requires `Self: Sized`
   |       this trait cannot be made into an object...
...
51 |     let updaters: Vec<Box<dyn Interface>> = vec![Box::new(Adder::default()), Box::new(Suber::default())];
   |                   ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Interface` cannot be made into an object

發生此錯誤是因為 trait Interface不滿足對象安全

  • 它必須不需要Self: Sized
  • 所有關聯的函數都必須有一個where Self: Sized bound,或者
    • 沒有任何類型參數(盡管允許使用生命周期參數),並且
    • 是一種除了接收器類型之外不使用Self的方法。
  • 它不能有任何關聯的常量。
  • 所有超特征也必須是對象安全的。

更新

您可以將trait Interface: Default + Sized更改為trait Interface (因為Default也需要Sized )。 不過不知道能不能滿足你的需求。 @UkonnRa

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM