gpt4 book ai didi

rust - 在Rust中,如何使自己具有 self 特质?

转载 作者:行者123 更新时间:2023-12-03 11:35:12 25 4
gpt4 key购买 nike

只是想知道如何将的特征与放入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

最佳答案

发生此错误是因为特征Interface不满足object safety

  • It must not require Self: Sized
  • All associated functions must either have a where Self: Sized bound, or
    • Not have any type parameters (although lifetime parameters are allowed), and
    • Be a method that does not use Self except in the type of the receiver.
  • It must not have any associated constants.
  • All supertraits must also be object safe.


更新
您可以将 trait Interface: Default + Sized更改为 trait Interface(因为 Default也需要 Sized)。但是我不知道这是否满足您的需求。 @UkonnRa

关于rust - 在Rust中,如何使自己具有 self 特质?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64095155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com