我正在研究一个protobuf Rust项目。为了解析消息,需要知道类型,因此ID(a u32
)被发送并与枚举(MessageType
)匹配。根据类型,该枚举值需要另一个匹配来确定实际类型。简化版本如下:
use protobuf::core::parse_from_bytes;
#[derive(Copy, Clone, Debug)]
pub enum MessageType {
Neither = 0,
TypeA = 1,
TypeB = 2
}
impl From<u32> for MessageType {
fn from(id: u32) -> Self {
match id {
1 => MessageType::TypeA,
2 => MessageType::TypeB
_ => MessageType::Neither
}
}
}
fn decode_message(&mut self, m_type: Option<MessageType>) -> Result<..., ....> {
// some code before...
let m = match m_type {
&Option::Some(MessageType::TypeA) => parse_from_bytes::<TypeA>(&mut (self.body.as_mut() as &mut [u8]))?,
&Option::Some(MessageType::TypeB) => parse_from_bytes::<TypeB>(&mut (self.body.as_mut() as &mut [u8]))?,
_ => panic!("unknown type")
};
// do something with m...
}
是否有更优雅的方式将通用消息类型绑定到枚举以消除decode_message
中所需的匹配?