控制流¶
包含条件分支、后置 if、then 以及多种循环形式。示例先用 while 与经典 for 展示不同循环结构,再用后置 if 与 then 体现表达式化控制流,最后用区间遍历展示范围循环。
use "std" -> std;
act[io.out] main() -> i32 {
var i32 i = 0;
while (i < 3) {
std.println("while loop");
i++;
}
for (var i32 j = 0; j < 3; j++) {
std.println(j);
}
std.println("even") if 2 % 2 == 0;
1 < 2 then std.println("then branch");
if (i == 3) {
std.println("i == 3");
} elif (i == 4) {
std.println("i == 4");
} else {
std.println("other");
}
for (val v : 1 .. 3) {
std.println(v);
}
return 0;
}
switch/match 示例:
展示基于值的 switch 与基于匹配的 match,二者都支持 else 兜底分支,语法结构相近便于替换。
use "std" -> std;
act[io.out] main() -> i32 {
val n = 2;
switch (n) {
1: { std.println("one"); }
2: { std.println("two"); }
else: { std.println("other"); }
}
match (n) {
1: { std.println("match one"); }
2: { std.println("match two"); }
else: { std.println("match other"); }
}
return 0;
}