| 1 | struct FixedStruct1 { |
| 2 | a int |
| 3 | b ?int |
| 4 | c ?int = 4 |
| 5 | } |
| 6 | |
| 7 | // struct FixedStruct2 { |
| 8 | // b ?int |
| 9 | // } |
| 10 | |
| 11 | struct Encoder {} |
| 12 | |
| 13 | struct Writer {} |
| 14 | |
| 15 | fn write1[T](val T) { |
| 16 | println(val) |
| 17 | } |
| 18 | |
| 19 | fn (wr &Writer) write2[T](val T) { |
| 20 | println(val) |
| 21 | } |
| 22 | |
| 23 | fn encode_struct[T](val T) map[string][]string { |
| 24 | wr := Writer{} |
| 25 | mut out := map[string][]string{} |
| 26 | $if T is $struct { |
| 27 | $for field in T.fields { |
| 28 | out[field.name] = []string{} |
| 29 | value := val.$(field.name) |
| 30 | $if field.typ is ?int { |
| 31 | // work if comment lines 27 and 28 |
| 32 | write1(value) |
| 33 | wr.write2(value) |
| 34 | out[field.name] << '${value:d}' |
| 35 | } $else { |
| 36 | write1(value) |
| 37 | wr.write2(value) |
| 38 | out[field.name] << value.str() |
| 39 | } |
| 40 | // This work well |
| 41 | $if field.is_option { |
| 42 | write1(value) |
| 43 | wr.write2(value) |
| 44 | out[field.name] << '${value:d}' |
| 45 | } $else { |
| 46 | write1(value) |
| 47 | wr.write2(value) |
| 48 | out[field.name] << value.str() |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | return out |
| 53 | } |
| 54 | |
| 55 | fn test_main() { |
| 56 | // cgen error: cannot convert 'struct _option_int' to 'int' |
| 57 | out := encode_struct(FixedStruct1{}) |
| 58 | assert out['a'] == ['0', '0'] |
| 59 | assert out['b'] == ['0', '0'] |
| 60 | assert out['c'] == ['4', '4'] |
| 61 | } |
| 62 | |