gpt4 book ai didi

rust - 如何使调用者看到方法的特征实现?

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

带有代码:

trait Msg {
fn apply_to_state(&self, state: &mut State);
}

trait ApplicableToStateOne: Msg {
fn apply_to_state(&self, state: &mut State) {
match state {
State::StateOne(s) => {
self.apply_to_state_one(s)
}
_ => {
//TODO: return an error
}
}
}
fn apply_to_state_one(&self, state_one: &mut StateOne);
}

#[derive(Debug, Clone)]
pub struct MsgA {
pub field_a: u8,
}

impl Msg for MsgA {}
impl ApplicableToStateOne for MsgA {
fn apply_to_state_one(&self, state_one: &mut StateOne) {
state_one.one_special += 31; // just a mutability test
}
}

// this is a stub for receiving different kinds of messages from the network
fn recv() -> Box<dyn Msg> {
Box::new(MsgA { field_a: 42 })
}

fn main() {
let mut state = State::StateOne(StateOne { common: 0, one_special: 1 });
for _ in 0..100 { // this would be loop, but that makes the playground timeout
let incoming = recv(); // this would block
incoming.apply_to_state(&mut state)
}
}
(游乐场: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7c89a2bbc765380fc002864e2be80e55)
编译器提示:
error[E0046]: not all trait items implemented, missing: `apply_to_state`
--> src/bin/sandbox6.rs:83:1
|
2 | fn apply_to_state(&self, state: &mut State);
| -------------------------------------------- `apply_to_state` from trait
...
83 | impl Msg for MsgA {}
| ^^^^^^^^^^^^^^^^^ missing `apply_to_state` in implementation
在我的(显然是不足的)理解中,我期望会调用 trait ApplicableToStateOneapply_to_state实现。
我怎样才能做到这一点?

更新:
更抽象地讲,这个问题是关于:
  • 从网络接收一个盒装的超特质对象,然后
  • 找出它具有哪个子特性,最后
  • 调用适合于子特征的方法(也许以某种方式通过 super 特征)。

  • 可以使用枚举而不是特征来完成所有操作,而只是冗长而已,但这会增加枚举的层次结构。
    具有枚举的层次结构是不好的,因为:
  • 它将不必要的字节添加到序列化中,并且因为
  • 只能有一个这样的层次结构,这会阻止以任何其他方式对消息进行分类。
  • 最佳答案

    您可以使用泛型来为实现Msg的所有内容实现ApplicableToStateOne:

    struct State {}

    trait Msg {
    fn apply_to_state(&self, state: &mut State);
    }

    trait ApplicableToStateOne: Msg {
    fn apply_to_state_one(&self, state: &mut State) {
    todo!();
    }
    }

    impl<T: ApplicableToStateOne> Msg for T {
    fn apply_to_state(&self, state: &mut State) {
    self.apply_to_state_one (state);
    }
    }

    #[derive(Debug, Clone)]
    pub struct MsgA {
    pub field_a: u8,
    }

    impl ApplicableToStateOne for MsgA {}
    // No need to implement Msg explicitly for MsgA
    Playground

    关于rust - 如何使调用者看到方法的特征实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63241273/

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