v2 / vlib / v / tests / comptime / comptime_generic_ret_test.v
48 lines · 42 sloc · 638 bytes · 6488041a749df9762348d019c4223908c476f2e2
Raw
1struct Parent {
2pub mut:
3 id int
4 name string
5 child Child
6 other Other
7}
8
9struct Child {
10pub mut:
11 id int
12 age int
13}
14
15struct Other {
16pub mut:
17 id int
18 name string
19}
20
21interface IdInterface {
22mut:
23 id int
24}
25
26fn 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
42fn 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