Skip to content

Latest commit

 

History

History
247 lines (243 loc) · 6.13 KB

11.enums.md

File metadata and controls

247 lines (243 loc) · 6.13 KB

Enums

  • Enum is a custom data type that is composed of variants.
  • Variants are values which are definite.
#[derive(Debug)]
enum KnightMove{
   Horizontal, Vertical
}
fn main() {
   // use enum
   let horizontal_move = KnightMove::Horizontal;
   let vertical_move = KnightMove::Vertical;
   // print the enum values
   println!("Move 1: {:?}", horizontal_move);
   println!("Move 2: {:?}", vertical_move);
}
  • enum with struct
enum Direction {
    Up(Point),
    Down(Point),
    Left(Point),
    Right(Point),
}
struct Point{
    x:i32,
    y:i32
}
  • enum with data-type
// make this `enum` printable with `fmt::Debug`.
#[derive(Debug)]
enum KnightMove{
   Horizontal(String), Vertical(String)
}
fn main() {
   // invoke an enum
   let horizontal_move = KnightMove::Horizontal("Left".to_string());
   let vertical_move = KnightMove::Vertical("Down".to_string());
   // print enum
   println!("Move 1: {:?}", horizontal_move);
   println!("Movw 2: {:?}", vertical_move);
}
  • Methods in Enums
#[derive(Debug)]
// declare an enum
enum TrafficSignal{
  Red, Green, Yellow
}
//implement a Traffic Signal methods
impl TrafficSignal{
  // if the signal is red then return
   fn is_stop(&self)->bool{
     match self{
       TrafficSignal::Red=>return true,
       _=>return false
     }
   }
}
  • Method control operator
enum KnightMove{
   Horizontal,Vertical
}
// print function 
fn print_direction(direction:KnightMove) {
   // match statement
   match direction {
      //execute if knight move is horizontal
      KnightMove::Horizontal => {
         println!("Move in horizontal direction");
      },
       //execute if knight move is vertical
      KnightMove::Vertical => {
         println!("Move in vertical direction");
      }
   }
}
  • enums can used like datatypes in structs
#[derive(Debug)]
//define an enum
enum KnightMove{
   Horizontal, Vertical
}
#[derive(Debug)]
// make this `struct` print values of type `enum`  with `fmt::Debug`.
struct Player {
   color:String,
   knight:KnightMove
}
  • Option and enum
fn main() {
   println!("{:?}", learn_lang("Rust"));
   println!("{:?}", learn_lang("Python"));
}
fn learn_lang(my_lang:&str)-> Option<bool> {
   if my_lang == "Rust" {
      Some(true)
   } else {
      None
   }
}
  • Optional Variable Value
//declare a struct
struct Course {
   code:i32,
   name:String,
   level: Option<String>, 
}
fn main() {
   //initialize
   let course1 = Course  {
      name:String::from("Rust"),
      level:Some(String::from("beginner")),
      code:130
   };
   let course2 = Course  {
      name:String::from("Javascript"),
      level:None,
      code:122
   };
   //access
   println!("Name:{}, Level:{} ,code: {}", course1.name, course1.level.unwrap_or("Level".to_string()), course1.code);
   println!("Name:{}, Level:{} ,code: {}", course2.name, course2.level.unwrap_or("No level defined!".to_string()), course2.code);
}
  • Index Out of Bound Exception
fn main() {
  // define a variable
  let str = String :: from("Educative");
  // define the index value to be found
  let index = 12;
  lookup(str, index);
}
fn lookup(str: String, index: usize) {
  let matched_index = match str.chars().nth(index){
    // execute if match found print the value at specified index 
     Some(c)=>c.to_string(),
     // execute if value not found
     None=>"No character at given index".to_string()
     };  
  println!("{}", matched_index);
}
  • is_some(), is_none() functions to identify the return type of variable of type Option

Result

  • Variants:
    • Ok(T), returns the success statement of type T
    • Err, returns the error statement of type E.
  • Result should be used as a return type for a function that can encounter error situations. Such functions can return an Ok value in case of success or an Err value in case of an error.
    fn main() {
       println!("{:?}",file_found(true)); // invoke function by passing true 
       println!("{:?}",file_found(false)); // invoke function by passing false
    }
    fn file_found(i:bool) -> Result<i32,bool> {
       if i { // if true
          Ok(200) // return Ok(200)
       } else { // if false
          Err(false) // return Err(false)
       }
    }
  • is_ok(), is_err() to check whether the variable of type Result is set to Ok or Err
    fn main() {
       let check1 = divisible_by_3(6);
       if check1.is_ok(){ // check if the function returns ok
          println!("The number is divisible by 3");
       }
       else{
          println!("The number is not divisible by 3");
    
       }
       let check2 = divisible_by_3(2);
       if check2.is_err(){ // check if the function returns error
          println!("The number is not divisible by 3");
       }
       else{
          println!("The number is divisible by 3");
    
       }
    }
    fn divisible_by_3(i:i32)->Result<String,String> {
       if i % 3 == 0 { // check i modulus 3
          Ok("Given number is divisible by 3".to_string())
       } else {
          Err("Given number is not divisible by 3".to_string())
       }
    }
  • Find If the Day Is a Weekend
    #[derive(Debug)]
    // declare an enum
    enum Days{
        Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
    }
    //implement Days methods
    impl Days{
        // if the day is a weekend
        fn is_weekend(&self)->i32{
          match self{
            &Days::Saturday=>return 1,
            &Days::Sunday=>return 1,
            _=>return 0
          }
        }
    }
    fn main() {
        let mut check_day = Days::Saturday;
        println!("Is Saturday a weekend ? : {}", check_day.is_weekend());
        check_day = Days::Monday;
        println!("Is Monday a weekend ? : {}", check_day.is_weekend());
    }
  • enum with struct and trait pattern
enum Shape{
    Rectangle {height:u32, width:u32},
    Circle(f64),
    Square(u32)
}
impl Shape {
    fn area(&self) -> f64 {
        match *self {
            Shape::Rectangle {width, height} => (width * height) as f64,
            Shape::Circle(ref r) => (3.14 * r) as f64,
            Shape::Square(ref s) => (s * s) as f64,
        }
    }   
}