Git repo: https://github.com/caveofprogramming/rust/
Enums
Enums let you specify a bunch of different possible options.
They look like this:
It’s possible to assign values to the different enum
constants:
We can also specify the types of values that will be associated with each enum
constant, and those can be a different collection of values for each constant.
Here’s I’ve used the above enum
type in defining the second. We can also use struct types in here.
We can create variables of an enum
type and assign them to any constant of that enum
type.
As of yet I have no idea how to check if one of these is equal to another, or get data out of it, but we’ll probably cover that next time.
Enums can also have methods, just like structs.
Options
There is a kind of predefined enum
in Rust call Option
. This has the constant values Some
and None
. All of these are imported in the Rust prelude, meaning we can refer to them without any kind of import statement.
Rust has no null type, so we have to use Option
instead.
Now we can be sure that value definitely refers to a valid value, and not to nothing.
If we actually want it to refer to “nothing”, we can write this, for example:
Since I’m assigning this to Option::None
(which we can refer to as just None
, since it’s part of the “prelude”), Rust doesn’t know what kind of thing I might want to assign it to, so it makes me specify the type.
I’ve made it mutable so I can reassign it to a valid value, which I can now do as follows:
As of yet I don’t know how to get values out of Option
, so hopefully we’ll cover that next time. It looks complex.