test_inline_switch.zig (1111B) - Raw
1 const std = @import("std"); 2 const expect = std.testing.expect; 3 const expectError = std.testing.expectError; 4 5 fn isFieldOptional(comptime T: type, field_index: usize) !bool { 6 const fields = @typeInfo(T).@"struct".fields; 7 return switch (field_index) { 8 // This prong is analyzed twice with `idx` being a 9 // comptime-known value each time. 10 inline 0, 1 => |idx| @typeInfo(fields[idx].type) == .optional, 11 else => return error.IndexOutOfBounds, 12 }; 13 } 14 15 const Struct1 = struct { a: u32, b: ?u32 }; 16 17 test "using @typeInfo with runtime values" { 18 var index: usize = 0; 19 try expect(!try isFieldOptional(Struct1, index)); 20 index += 1; 21 try expect(try isFieldOptional(Struct1, index)); 22 index += 1; 23 try expectError(error.IndexOutOfBounds, isFieldOptional(Struct1, index)); 24 } 25 26 // Calls to `isFieldOptional` on `Struct1` get unrolled to an equivalent 27 // of this function: 28 fn isFieldOptionalUnrolled(field_index: usize) !bool { 29 return switch (field_index) { 30 0 => false, 31 1 => true, 32 else => return error.IndexOutOfBounds, 33 }; 34 } 35 36 // test