Enums
Enums are custom types, defined like this:
Using enums:
Enums may have some data attached to them:
or
In this case the enum members become constructors. It’s an alternative to creating a struct, e.g.:
Enum Methods
Similarly to structs, enums can have methods:
Option Enum
Similarly to some .NET libraries (like
Optional) Rust provides an Option
enum to
be used instead of null
.
Option
provides us with explicit information that a variable might not have
any actual value. In some other languages variable a
of type String
could be
some string or null
. In Rust, a variable of type String
has to have some
string (even empty one)! It’s another example of how Rust focuses on safety.
Match
match
is quite useful with enums (like Option<T>
):
An example of handling errors:
If let
if let
is a syntax sugar for match
. It is useful when we’re interested only
in one of match
patterns:
Some(max)
is a pattern, while config_max
is a value being matched.