Reputation: 56
I am learning rust and have come across enums. I understand why they might be useful for organising variables. It is also far more difficult to access data in said enums. My question comes down to this: why do people use enums and is there an easy way to retrieve the data from them?
My current solution to the latter is to use a match statement:
enum Breakfast {
Toast(String),
}
fn main() {
let breakfast = Breakfast::Toast(String::from("Buttered"));
match breakfast {
Breakfast::Toast(t) => println!("{}",t),
_ => panic!("I'm Hungry!"),
}
}
This is a very inefficient, are there any other ways to do this?
Upvotes: 0
Views: 1662
Reputation: 41
I think the previous answer misinterpreted your question.
A simple let statement can also destructure the enum. However usually there is more than one enum variant.
enum Breakfast {
Toast(String),
}
fn main() {
let breakfast = Breakfast::Toast(String::from("Buttered"));
let Breakfast::Toast(t) = breakfast;
println!("{}", t);
}
enum Breakfast {
Toast(String),
Eggs(String)
}
fn main() {
let breakfast = Breakfast::Toast(String::from("Buttered"));
let _breakfast2 = Breakfast::Eggs(String::from("Over Easy"));
if let Breakfast::Toast(t) = breakfast {
println!("{}", t);
} ;
}
Upvotes: 1
Reputation: 42632
I understand why they might be useful for organising variables.
I've got no idea what that means.
My question comes down to this: why do people use enums
Because they allow making invalid states unrepresentable1: enums allow exclusive representations.
and is there an easy way to retrieve the data from them?
match
, if let
, utility functions which bundle the access or even provides higher-level operations on them.
Your example is too detached from any information to make any judgement upon it (e.g. on whether you're misusing enums) aside from "the compiler literally tells you that the _
case is useless".
But for instance the Option
and Result
types are enums. Because an Option
is either Some
or None
, and a Result
is either Ok
or Err
. Enums allow this information to be part of the typesystem, and thus the compiler to assist with checking it.
1: though a common issue is what states are actually invalid, there are domains where it's not clear cut, the validity of a given datum can even vary based on domain!
Upvotes: 1