Concise Control Flow with if let

고승우·2023년 7월 4일
0
post-thumbnail

Concise Control Flow with if let

if let syntax는 한 가지와 나머지를 matching하는 pattern에서 깔끔하게 handle할 수 있다. config_max 에서 Option<u8>과 matching 하는 경우 Some 에서만 코드를 실행시키고 싶은 경우다.

    let config_max = Some(3u8);
    match config_max {
        Some(max) => println!("The maximum is configured to be {}", max),
        _ => (),	 // _(the other) -> empty tuple 
    }

만약 value가 Some이라면, 해당 값은 max에 binding 되고, None인 경우에는 코드가 작동하지 않는다. 상용구를 추가하지 않고 match 표현식을 만족시키기 위해서 _ => () 를 추가해야 하지만 if let문을 사용하면

    let config_max = Some(3u8);
    if let Some(max) = config_max {
        println!("The maximum is configured to be {}", max);
    }

if let을 사용하여 타이핑을 줄이고 가독성을 높인다. 하지만, match 구문의 철저한 확인을 활용하지는 못한다.
else 구문을 활용하여 _ case를 처리할 수도 있다.

    let mut count = 0;
    if let Coin::Quarter(state) = coin {
        println!("State quarter from {:?}!", state);
    } else {
        count += 1;
    }

match를 사용할 때, if let 또한 사용할 수 있음을 잊지 말자.

profile
٩( ᐛ )و 

0개의 댓글