liveBook · Manning

Labeled block

As explained in Systems Programming with Zig

A labeled block is a named Zig block that can be exited with break and can yield a value.

A labeled block gives a scope a name and can yield a value without a separate function. Write the label before the block, as in `a: { ... }`, and exit it with `break :a value`. Labels also distinguish nested blocks. section 4.1.3

Listing 4.5 Using labels
const result: i32 = a: {
    const some_resource: Resource = .init();
    defer some_resource.deinit(); #1

    if (some_resource.some_condition()) {
        break :a 0;
    }
    break :a 1;
};

The block yields either 0 or 1 while keeping resource cleanup inside its scope. section 4.1.3

Listing 4.6 Using our parser
const words = blk: { #1
    @setEvalBranchQuota(1_000_000); #2
    break :blk parseWordlist(@embedFile("words.txt")); #3
};

A labeled block sets the compile-time branch quota and yields the parsed contents of an embedded wordlist. section 4.1.3

How Systems Programming with Zig covers it

How deep it goes
Explains label syntax, value-bearing breaks, early exits, and targeting nested blocks.
Examples
Demonstrates scoped resource cleanup and compile-time parsing of an embedded wordlist.
What you can do after
Evaluate/understand how to use labeled blocks to scope resources and produce values.
How it connects
Connects labeled blocks to scopes, defer, loops, and compile-time evaluation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.