Enums in Rust behave like you would expect in most C based languages. You can also implement methods on enum types. Both instance and “type” methods.
You declare these methods in the same way that you declare methods on a struct, using the impl keyword followed by the enum’s name.
Here is an example of an enum with a constructor-like method and two instance methods.
Compiling and running this program would output the following result:
Now let’s try something a little bit more complex. The following is a enum type I wrote for an actual application. To get more familiar with Rust, I am porting my height map generator that I used for my Ruby game project.
The following enum generates random coordinates for a particle drop point (the algorithm I use for generating the map is the particle deposition algorithm). The formula to calculate the coordinates varies depending on how many times we have called it.
Here is the enum type:
And here is how it’s called:
Contrary to the first example, when I change the state of the enum I return a new instance instead of mutating the current one.