Categorizing with Enumerations
Hands-on Rust — by Herbert Wolverson (30 / 120)
👈 Storing a Variable Amount of Data with Vect ors | TOC | Wrap-Up 👉
The bouncer would like even more functionality. They’d like to know how to treat different visitors and if they can drink alcohol. The final set of improvements to the visitor list are:
- Store an action associated with a visitor: admit them, admit them with a note, refuse entry, or mark them as probationary treehouse members.
- Store the visitor’s age, and forbid them from drinking if they’re under 21.
Enumerations
Rust lets you define a type that can only be equal to one of a set of predefined values. These are known as enumerations, and are declared with the enum keyword. You are going to define an enumeration listing each of the four actions associated with a visitor. Rust enumerations are very powerful, and can include data — and even functions — for each enumeration entry.[32]
Towards the top of the file — outside of any functions — create a new enumeration with the following code:
FirstStepsWithRust/treehouse_guestlist_enum/src/main.rs
①#[derive(Debug)]
②enum VisitorAction {
③ Accept,
④ AcceptWithNote { note: String },
Refuse,
Probation,
⑤}
①
Enumerations can derive functionality, just like structs. Deriving Debug…