조건문
- 일반적인 if 조건문은 다른 언어와 비슷하게 사용할 수 있다.
fn main() { let number = 6;
if number % 4 == 0 { println!("number is divisible by 4"); } else if number % 3 == 0 { println!("number is divisible by 3"); } else if number % 2 == 0 { println!("number is divisible by 2"); } else { println!("number is not divisible by 4, 3, or 2"); }}
match
- match라는 흐름 제어 연산자를 사용할 수 있다. (Kotlin의 when, Java 또는 C의 switch와 같은 역할이다.)
enum Coin { Penny, Nickel, Dime, Quarter,}
fn value_in_cents(coin: Coin) -> u32 { match coin { Coin::Penny => 1, Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter => 25, }}
if let
- if와 let을 조합하여 하나의 패턴만 매칭 시키는 구문을 작성할 수 있다.
let some_u8_value = Some(0u8);match some_u8_value { Some(3) => println!("three"), _ => (),}
// 위 코드와 동일if let Some(3) = some_u8_value { println!("three");}
패턴 매칭
- 구조체에 대한 match 조건을 아래와 같이 작성할 수 있다.
- 조건문에서 새로운 변수명을 사용하여 값을 캡처할 수 있다.
struct Foo { x: (u32, u32), y: u32,}
#[rustfmt::skip]fn main() { let foo = Foo { x: (1, 2), y: 3 }; match foo { Foo { x: (1, b), y } => println!("x.0 = 1, b = {b}, y = {y}"), Foo { y: 2, x: i } => println!("y = 2, x = {i:?}"), Foo { y, .. } => println!("y = {y}, other fields were ignored"), }}
- 배열이나 튜플, 슬라이스도 그 요소들에 대해 패턴 매칭으로 분해할 수 있다.
..
는 요소 개수에 상관없이 매치될 수 있다.[.., b]
나[a@.., b]
와 같은 패턴으로 꼬리 부분을 매칭할 수 있다.
#[rustfmt::skip]fn main() { let triple = [0, -2, 3]; println!("Tell me about {triple:?}"); match triple { [0, y, z] => println!("First is 0, y = {y}, and z = {z}"), [1, ..] => println!("First is 1 and the rest were ignored"), _ => println!("All elements were ignored"), }}
- 패턴 뒤에 추가 불리언 표현식인 가드(guard, 조건식)를 덧붙일 수 있다.
- 패턴에 정의된 변수를 가드의 표현식에서 사용할 수 있다.
#[rustfmt::skip]fn main() { let pair = (2, -2); println!("Tell me about {pair:?}"); match pair { (x, y) if x == y => println!("These are twins"), (x, y) if x + y == 0 => println!("Antimatter, kaboom!"), (x, _) if x % 2 == 1 => println!("The first one is odd"), _ => println!("No correlation..."), }}
반복문
- for, while, loop 등의 반복문을 제공한다.
fn main() {
// for 반복문 // for 반복문은 자동으로 into_iter()를 호출한 다음 이를 반복한다. let v = vec![10, 20, 30];
for x in v { println!("x: {x}"); }
for i in (0..10).step_by(2) { println!("i: {i}"); }
// while 반복문 let mut x = 10; while x != 1 { x = if x % 2 == 0 { x / 2 } else { 3 * x + 1 }; } println!("Final x: {x}");
// 무한 루프를 만드는 loop 키워드 // while, for와 달리 최소한 한 번은 루프문을 수행하는 것이 보장된다. let mut x = 10; loop { x = if x % 2 == 0 { x / 2 } else { 3 * x + 1 }; if x == 1 { break; } } println!("Final x: {x}");}
while let
- while와 let을 조합하여 패턴을 매칭 시키는 구문을 작성할 수 있다.
fn main() { let v = vec![10, 20, 30]; let mut iter = v.into_iter();
while let Some(x) = iter.next() { println!("x: {x}"); }}
참고
- https://rinthel.github.io/rust-lang-book-ko/ch06-03-if-let.html
- https://google.github.io/comprehensive-rust/ko/control-flow/if-let-expressions.html
- https://google.github.io/comprehensive-rust/ko/control-flow/novel.html
- https://google.github.io/comprehensive-rust/ko/pattern-matching/destructuring-enums.html