简体   繁体   中英

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; using 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 ". 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 .

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM