test_switch.zig (1930B) - Raw
1 const std = @import("std"); 2 const builtin = @import("builtin"); 3 const expect = std.testing.expect; 4 5 test "switch simple" { 6 const a: u64 = 10; 7 const zz: u64 = 103; 8 9 // All branches of a switch expression must be able to be coerced to a 10 // common type. 11 // 12 // Branches cannot fallthrough. If fallthrough behavior is desired, combine 13 // the cases and use an if. 14 const b = switch (a) { 15 // Multiple cases can be combined via a ',' 16 1, 2, 3 => 0, 17 18 // Ranges can be specified using the ... syntax. These are inclusive 19 // of both ends. 20 5...100 => 1, 21 22 // Branches can be arbitrarily complex. 23 101 => blk: { 24 const c: u64 = 5; 25 break :blk c * 2 + 1; 26 }, 27 28 // Switching on arbitrary expressions is allowed as long as the 29 // expression is known at compile-time. 30 zz => zz, 31 blk: { 32 const d: u32 = 5; 33 const e: u32 = 100; 34 break :blk d + e; 35 } => 107, 36 37 // The else branch catches everything not already captured. 38 // Else branches are mandatory unless the entire range of values 39 // is handled. 40 else => 9, 41 }; 42 43 try expect(b == 1); 44 } 45 46 // Switch expressions can be used outside a function: 47 const os_msg = switch (builtin.target.os.tag) { 48 .linux => "we found a linux user", 49 else => "not a linux user", 50 }; 51 52 // Inside a function, switch statements implicitly are compile-time 53 // evaluated if the target expression is compile-time known. 54 test "switch inside function" { 55 switch (builtin.target.os.tag) { 56 .fuchsia => { 57 // On an OS other than fuchsia, block is not even analyzed, 58 // so this compile error is not triggered. 59 // On fuchsia this compile error would be triggered. 60 @compileError("fuchsia not supported"); 61 }, 62 else => {}, 63 } 64 } 65 66 // test