| 1 | struct Parent { |
| 2 | pub mut: |
| 3 | id int |
| 4 | name string |
| 5 | child Child |
| 6 | other Other |
| 7 | } |
| 8 | |
| 9 | struct Child { |
| 10 | pub mut: |
| 11 | id int |
| 12 | age int |
| 13 | } |
| 14 | |
| 15 | struct Other { |
| 16 | pub mut: |
| 17 | id int |
| 18 | name string |
| 19 | } |
| 20 | |
| 21 | interface IdInterface { |
| 22 | mut: |
| 23 | id int |
| 24 | } |
| 25 | |
| 26 | fn insert_ids[T](val T) !T { |
| 27 | mut clone := val |
| 28 | |
| 29 | $for field in T.fields { |
| 30 | $if field.typ is $struct { |
| 31 | clone.$(field.name) = insert_ids(val.$(field.name))! |
| 32 | } |
| 33 | } |
| 34 | $if T is IdInterface { |
| 35 | clone.id = 1 |
| 36 | } $else { |
| 37 | return error('${T.name} does not have an id field!') |
| 38 | } |
| 39 | return clone |
| 40 | } |
| 41 | |
| 42 | fn test_main() { |
| 43 | inserted := insert_ids(Parent{ |
| 44 | name: 'test' |
| 45 | })! |
| 46 | assert inserted.child.id == 1 |
| 47 | assert inserted.other.id == 1 |
| 48 | } |
| 49 | |