Localized V2 rewrite for this language is in progress. Showing English-first content for now.

控制流

条件分支、循环,以及 match 表达式。

控制流

Sounio 提供熟悉的控制流结构: ifwhileformatch

if / else

if 是表达式,因此你可以绑定它的结果:

let max = if a > b { a } else { b }

while

fn main() with IO {
    var count = 0
    while count < 3 {
        println(count)
        count = count + 1
    }
}

for-in

区间:

fn main() with IO {
    // Exclusive range: 0..5
    var sum = 0
    for i in 0..5 {
        sum = sum + i
    }

    // Inclusive range: 0..=5
    var sum_inclusive = 0
    for i in 0..=5 {
        sum_inclusive = sum_inclusive + i
    }
}

数组与 Vec<T>:

fn main() with IO {
    let arr = [10, 20, 30]
    for x in arr {
        println(x)
    }

    let vec: Vec<i32> = [1, 2, 3, 4]
    for x in vec {
        println(x)
    }
}

breakcontinue:

fn main() with IO {
    for i in 0..10 {
        if i % 2 == 0 {
            continue
        }
        if i >= 7 {
            break
        }
        println(i)
    }
}

match

fn main() with IO {
    let x = 1
    let y = match x {
        0 => 10
        1 => 20
        _ => 30
    }

    println(y)
}

规范说明: match guard、范围模式以及更丰富的 enum 模式属于语言演进方向。为了可移植的示例,建议优先使用最简单的 match 形式。

下一步