| ... | ... | @@ -4311,10 +4311,11 @@ test "enum literals with switch" { |
| 4311 | 4311 | {#code_end#} |
| 4312 | 4312 | {#header_close#} |
| 4313 | 4313 | |
| 4314 | | {#header_open|Inline switch#} |
| 4314 | {#header_open|Inline Switch Prongs#} |
| 4315 | 4315 | <p> |
| 4316 | 4316 | Switch prongs can be marked as {#syntax#}inline{#endsyntax#} to generate |
| 4317 | | the prong's body for each possible value it could have: |
| 4317 | the prong's body for each possible value it could have, making the |
| 4318 | captured value {#link|comptime#}. |
| 4318 | 4319 | </p> |
| 4319 | 4320 | {#code_begin|test|test_inline_switch#} |
| 4320 | 4321 | const std = @import("std"); |
| ... | ... | @@ -4324,9 +4325,9 @@ const expectError = std.testing.expectError; |
| 4324 | 4325 | fn isFieldOptional(comptime T: type, field_index: usize) !bool { |
| 4325 | 4326 | const fields = @typeInfo(T).Struct.fields; |
| 4326 | 4327 | return switch (field_index) { |
| 4327 | | // This prong is analyzed `fields.len - 1` times with `idx` being a |
| 4328 | | // unique comptime-known value each time. |
| 4329 | | inline 0...fields.len - 1 => |idx| @typeInfo(fields[idx].type) == .Optional, |
| 4328 | // This prong is analyzed twice with `idx` being a |
| 4329 | // comptime-known value each time. |
| 4330 | inline 0, 1 => |idx| @typeInfo(fields[idx].type) == .Optional, |
| 4330 | 4331 | else => return error.IndexOutOfBounds, |
| 4331 | 4332 | }; |
| 4332 | 4333 | } |
| ... | ... | @@ -4350,6 +4351,16 @@ fn isFieldOptionalUnrolled(field_index: usize) !bool { |
| 4350 | 4351 | 1 => true, |
| 4351 | 4352 | else => return error.IndexOutOfBounds, |
| 4352 | 4353 | }; |
| 4354 | } |
| 4355 | {#code_end#} |
| 4356 | <p>The {#syntax#}inline{#endsyntax#} keyword may also be combined with ranges:</p> |
| 4357 | {#code_begin|syntax|inline_prong_range#} |
| 4358 | fn isFieldOptional(comptime T: type, field_index: usize) !bool { |
| 4359 | const fields = @typeInfo(T).Struct.fields; |
| 4360 | return switch (field_index) { |
| 4361 | inline 0...fields.len - 1 => |idx| @typeInfo(fields[idx].type) == .Optional, |
| 4362 | else => return error.IndexOutOfBounds, |
| 4363 | }; |
| 4353 | 4364 | } |
| 4354 | 4365 | {#code_end#} |
| 4355 | 4366 | <p> |