Skip to content

Latest commit

 

History

History
80 lines (63 loc) · 1.8 KB

4.md

File metadata and controls

80 lines (63 loc) · 1.8 KB

Enums and Patterns Matching

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 enum are reffered to as variants. i.e Red, Blue and Yellow are 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),
    }

Options

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;

Match

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 - let statements can be used as alternative to write the equivalent of match that has only one case

       let something = Some(Color::Yellow);
    
      if let something = Some(Color::Yellow) {
          println!("{}", "Probably roasted already");
      }