This commit is contained in:
2026-01-19 05:43:29 +09:00
parent 40f41a4fd0
commit 0f6fddd794
36 changed files with 1724 additions and 0 deletions

36
guide/language/switch.zig Normal file
View File

@@ -0,0 +1,36 @@
const expect = @import("std").testing.expect;
// Zig's switch works as both a statement and an expression.
// The types of all branches must coerce to the type which is being switched upon.
// All possible values must have an associated branch - values cannot be left out.
// Cases cannot fall through to other branches.
// An example of a switch statement. The else is required to satisfy the exhaustiveness of this switch.
test "switch statement" {
var x: i8 = 10;
switch (x) {
-1...1 => {
x = -x;
},
10, 100 => {
//special considerations must be made
//when dividing signed integers
x = @divExact(x, 10);
},
else => {},
}
try expect(x == 1);
}
// Here is the former, but as a switch expression.
test "switch expression" {
var x: i8 = 10;
x = switch (x) {
-1...1 => -x,
10, 100 => @divExact(x, 10),
else => x,
};
try expect(x == 1);
}
// Now is the perfect time to use what you've learned and solve a problem together.