enums or enumerations are datatypes that allow you to define a type which can have a fixed set of distinct values.
enum Color {
Red,
Blue,
Yellow,
}-
the distinct values in an
enumare reffered to as variants. i.eRed,BlueandYelloware variants. -
enums just like structs can also have methods
impl Color { fn get_color(self) -> &'static str { match self { Color::Red => "from mars", Color::Blue => "from the ocean", Color::Yellow => "from the sun", } } } let color = Color::Red; color.get_color(); // from mars
-
enums can hold multiple types
-
enums can have associated values
enum Cars{ Mercedes(String), Ford(i32), Tesla(bool), }
it allows us to allow for a value to be something or to be nothing which is comparable to null in javascript.
Option is important when we want the code to run if we have some T, or we want to have null || nothing
let some_num = Some(5);
let some_str = Some("a string");
let nothing: Option<i32> = None;allows us to compare a value against a series of patterns and execute code if the value matches. matches in rust are exhaustive, meaning we need to explicitly define the cases or add a catchall.
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
_ => Some(0), // catch all
}
}
let five = Some(5);
let six = plus_one(five);-
if - letstatements can be used as alternative to write the equivalent ofmatchthat has only one caselet something = Some(Color::Yellow); if let something = Some(Color::Yellow) { println!("{}", "Probably roasted already"); }