| 1 | struct Struct { |
| 2 | mut: |
| 3 | a string |
| 4 | b int |
| 5 | } |
| 6 | |
| 7 | fn decode_string[T](mut value T) { |
| 8 | value = 'gg' |
| 9 | } |
| 10 | |
| 11 | fn decode_string_int[T](mut value T) { |
| 12 | value = 123 |
| 13 | } |
| 14 | |
| 15 | fn decode[T]() T { |
| 16 | key := 'a' |
| 17 | mut result := T{} |
| 18 | $for field in T.fields { |
| 19 | $if field.typ is string { |
| 20 | decode_string(mut result.$(field.name)) |
| 21 | } $else $if field.typ is int { |
| 22 | decode_string_int(mut result.$(field.name)) |
| 23 | } |
| 24 | } |
| 25 | return result |
| 26 | } |
| 27 | |
| 28 | fn test_main() { |
| 29 | assert decode[Struct]() == Struct{ |
| 30 | a: 'gg' |
| 31 | b: 123 |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | struct OptionStruct { |
| 36 | mut: |
| 37 | v ?int |
| 38 | } |
| 39 | |
| 40 | fn decode_option_int[T](mut value T) { |
| 41 | $if T is int { |
| 42 | value = 42 |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | fn decode_option[T]() T { |
| 47 | mut result := T{} |
| 48 | $for field in T.fields { |
| 49 | $if field.typ is $option { |
| 50 | decode_option_int(mut result.$(field.name) ?) |
| 51 | } |
| 52 | } |
| 53 | return result |
| 54 | } |
| 55 | |
| 56 | fn test_comptime_option_payload_mut_generic() { |
| 57 | result := decode_option[OptionStruct]() |
| 58 | assert result.v? == 42 |
| 59 | } |
| 60 | |