[英]How can I dynamically determine the variant of an enum
I want to implement a module that encapsulates different types of messages with different types and quantity of fields that enables to send and receive them using the same send
and receive
functions, and then determine what variant of the message is, with what fields;我想实现一个模块,用不同类型和数量的字段封装不同类型的消息,以便使用相同的
send
和receive
函数发送和接收它们,然后确定消息的变体是什么,具有哪些字段; using match
.使用
match
。
I have the following enum and functions (simplified):我有以下枚举和函数(简化):
pub enum Message {
Start { field1 : type1 },
End { field2 : type2 },
}
impl Message {
pub fn send( &self ) {
send(self);
}
pub fn receive( &mut self ) {
*self = receive();
}
}
I want to use them as follows:我想按如下方式使用它们:
Send:发送:
let message = Message::Start;
message.send();
Receive收到
let message = Message;
message.receive();
match message {
Start{field1} => { ... }
End{field2} => { ... }
};
When calling the receive
function, I get a compiler error that says " use of possibly-uninitialized message
".调用
receive
function 时,我收到一个编译器错误,显示“使用可能未初始化的message
”。 It makes sense because this variable has not been initialized.这是有道理的,因为这个变量还没有被初始化。 How can I achieve this behavior with no errors?
我怎样才能在没有错误的情况下实现这种行为?
It sounds like you're looking for an associated function which returns a Message
.听起来您正在寻找一个关联的 function ,它返回一个
Message
。
impl Message {
pub fn receive() -> Message {
// Do whatever and return a Message::Start or Message::End as needed.
}
}
// To call...
let my_message = Message::receive();
Associated functions are sort of like static functions in C++, and they use ::
on the type name itself as the call syntax.关联函数有点像 C++ 中的 static 函数,它们在类型名称本身上使用
::
作为调用语法。 At runtime, it's just another ordinary function, but it's in the Message
namespace so it's easier to find for programmers at write time.在运行时,它只是另一个普通的 function,但它位于
Message
命名空间中,因此程序员在编写时更容易找到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.