Rust

RUST Documentation 따라 공부하기 11

2019.12.30


The match Control Flow Operator

match allows you to compare a value against a series of patterns and then execute code based on which pattern matches.

enum Coin {
  Penny,
  Nickel,
  Dime,
  Quarter,
}

fn value_in_cents(coin: Coin) -> u8 {
  match coin {
    Coin::Penny => {
      println!("Lucky penny!");
      1
    },
    Coin::Nickel => 5,
    Coin::Dime => 10,
    Coin::Quarter => 25,
  }
}

Patterns that Bind to Values

#[derive(Debug)]
enum UsState {
  Alabama,
  Alaska,
}

enum Coin { 
  Penny,
  nickel,
  Dime,
  Quarter(UsState)
}

fn value_in_cents(coin: Coin) -> u8 {
  match coin {
    Coin::Penny => 1,
    Coin::Nickel => 5,
    Coin::Dime => 10,
    Coin::Quarter(state) => {
      println!("State quarter from {:?}!", state);
      25
    },
  }
}
value_in_cents(Coin::Quarter(UsState::Alaska));

Matching with Option<T>

fn plus_one(x: Option<i32>) -> Option<i32> {
  match x {
    None => None, // should handle the None case
    Some(i) => Some(i+1),
  }
}
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);

The _ Placeholder

let some_u8_value = 0u8;
match some_u8_value {
  1 => println!("one"),
  3 => println!("three"),
  _ => (),
}

Concise Control Flow with if let

if let syntax lets you combine if and let into a less verbose way to handle values that match one pattern while ignoring the rest.

let some_u8_value = Some(0u8);
match some_u8_value {
  Some(3) => println!("three"),
  _ => (),
}

// instead,
if let Some(3) = some_u8_value {
  println!("three");
}
  • Using if let : less typing, less indentation, less boilerplate code
  • However, you lose the exhaustive checking that match enforces.