Learning Zig from the official language reference.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
zig-langref/switch.zig

81 lines
1.6 KiB

const std = @import("std");
const mem = std.mem;
const debug = std.debug;
const testing = std.testing;
test "simple switch" {
const a = 10;
const zz = 103;
const b = switch (a) {
1, 2, 3 => 0,
5...100 => 1,
101 => blk: {
const c = 5;
break :blk c + zz;
},
zz => zz,
comptime blk: {
const x = 1;
const y = 2;
break :blk x + y;
} => 100,
else => 99,
};
testing.expectEqual(1, b);
}
const os_msg = switch (std.Target.current.os.tag) {
.macos => "darwin",
.linux => "linux",
else => "something else",
};
test "global switches" {
testing.expect(mem.eql(u8, "darwin", os_msg));
}
test "switch inside functions" {
switch (std.Target.current.os.tag) {
.fuchsia => {
@compileError("We don't do evil");
},
else => {},
}
}
const Point = struct {
x: i32,
y: i32,
};
const Item = union(enum) { a: u32, b: Point, c, d: u32 };
test "switch on tagged unions" {
var a = Item{ .b = Point{ .x = 100, .y = 200 } };
switch (a) {
.b => |*p| {
debug.print("Got a point: {}\n", .{p});
debug.print("Updating it now...\n", .{});
p.x += 100;
p.y -= 100;
},
else => unreachable,
}
testing.expectEqual(a.b.x, 200);
testing.expectEqual(a.b.y, 100);
}
const Color = enum { auto, on, off };
test "exhaustive switching" {
const color = Color.off;
switch (color) {
.auto => {},
else => {},
}
}