Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make an Enum from struct

I want to make an enum from a struct.

The definitions:

struct Point {
    x: u8,
    y: u8,
}

enum Message {
    Move { x: u8, y: u8 },
    nothing,
}

So if I have instantiated a Point in my code, how can I make a Message from the struct?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried this code:

Message::Move(Point { x: 10, y: 15 })

But this code throws an error saying

error[E0423]: expected function, tuple struct or tuple variant, found struct variant `Message::Move`

>Solution :

Your enum variant can simply contain an instance of the struct.

enum Message {
  Move(Point),
  NoMessage,
}

Then the syntax you wanted will work as-is.

Message::Move(Point { x: 10, y: 15 })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading