有時候會需要寫一些比較複雜的多層迴圈程式,但這時如何要使用 break
或 continue
時會沒辦法控制要對哪一層迴圈進行。對於這種情況,只要為迴圈打上標籤,就可以明確指定了。
while
只要在 while
前打上 LABEL:
,這個 While-loop 就會被標記,隨後只要使用 break: LABEL
或 continue: LABEL
就可以了
const print = @import("std").debug.print;
pub fn main() void { outer: while (true) { var val: u16 = 0;
while (true) { print("Value: {}\n", .{val}); val += 1;
if (val == 4) { print("Break\n", .{}); break :outer; } } }}
Value: 0Value: 1Value: 2Value: 3Break
for
For-loop 也是相同的方式。
const print = @import("std").debug.print;
pub fn main() void { outer: for (1..100) |_| { for (1..10) |i| { print("Value: {}\n", .{i}); if (i == 4) { print("Break\n", .{}); break :outer; } } }}
Value: 0Value: 1Value: 2Value: 3Break
Block
Zig 的區塊 Block 可以作為表達式回傳值。
這個範例提供一個類似 C/C++ 的 #ifdef
預處理器條件編譯的寫法。
const print = @import("std").debug.print;
const DEBUG = false;
pub fn main() void { const mode = blk: { if (DEBUG) { break :blk "Debug"; } else { break :blk "Production"; } };
print("Running in {s} mode", .{mode});}
Running in Production mode
參考
- Labelled Loops | zig.guide
- Labelled Blocks | zig.guide
- while: Documentation - The Zig Programming Language
- for: Documentation - The Zig Programming Language
本文以 Zig 0.13.0
為主。並同時發佈在: