javier
javier

Reputation: 192

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?

Upvotes: 2

Views: 293

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70257

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.

Upvotes: 5

Related Questions