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?
selfforreceive? Can't it be an associated functionfn receive() -> Self?Messageto exist. What is a default message supposed to be? Why should a message send and receive itself? Shouldn't it be the job of another component?receiveis supposed to get an uninitializedmessageand initialize it. That's just not a feature of Rust.MaybeUninit<Message>but that's fraught with perils and requiresunsafe.