Victoree's Blog

[5] 흐름제어 [for, loop, while ...] 본문

Rust

[5] 흐름제어 [for, loop, while ...]

victoree 2023. 3. 2. 01:43
728x90

흐름제어

if 문

let mut x = 10;
x = if x % 2 == 0 {
    x / 2
} else {
    3 * x + 1
};

if 는 표현식으로도 사용할 수 있다. 표현식 뒤에는 ;이 붙는다.
블록은 타입과 값을 갖는다. 그래서 return을 했을 때에는 type 추론이 어려워서, 함부로 return을 사용하면 안된다.
예를 들어, 세미콜론 없이 {} 블록을 반환하는 경우 usize의 타입을 갖는다.

fn fibo(x: i32) -> i32 {
    if x == 0 { // This starts a block
        0 // First implicit return
    }
    else if x == 1 { // This also starts a block
        1 // First implicit return
    } // Therefore this entire if/else statement is an implicit return unless its output
      // is suppressed with a semicolon.

    fibo(x-1) + fibo(x-2) // Here we try to return again, which confuses rust!
    // 위 문을 else 로 감싸면 문제 해결됨
}

0, 1 이라는 명확한 값을 리턴하는 것과 재귀로 다시 함수를 호출하는 건 rust 컴파일러를 혼란스럽게 한다.

if let || while let

let v = vec![10, 20, 30];
let mut iter = v.into_iter();

while let Some(x) = iter.next() {
    println!("x: {x}");
}

위와 같이 사용되는데, into_iter() 함수는 next()가 호출될 때마다 Option가 반환되던지, None을 반환한다.
신기한 부분은 비교연산자가 == 이 아니라 = 이라는 점!

Loop와 Label

#![allow(unreachable_code)]

fn main() {
    'outer: loop {
        println!("Entered the outer loop");

        'inner: loop {
            println!("Entered the inner loop");

            // This would break only the inner loop
            //break;

            // This breaks the outer loop
            break 'outer;
        }

        println!("This point will never be reached");
    }

    println!("Exited the outer loop");
}

중첩된 루프를 다룰 때에는 break와 continue 구문을 사용하려면 반드시 어떤 loop에 대한 명령인지 명시적으로 붙여주어야 한다.

For

for i in (0..10).step_by(2) {
    println!("i: {i}");
}

(0..10) 은 stp::ops::Range 타입으로, step_by(usize), len(), is_empty() 등의 함수를 지원한다.
Range Struct

728x90
Comments