v2 / vlib / v / tests / comptime / comptime_field_selector_test.v
79 lines · 68 sloc · 1.2 KB · 6488041a749df9762348d019c4223908c476f2e2
Raw
1struct Foo {
2 immutable int
3mut:
4 test string
5 name string
6}
7
8enum TestEnum {
9 one = 1
10}
11
12struct TestStruct {
13 test TestEnum
14}
15
16fn comptime_field_selector_read[T]() []string {
17 mut t := T{}
18 t.name = '2'
19 t.test = '1'
20 mut value_list := []string{}
21 $for f in T.fields {
22 $if f.typ is string {
23 value_list << t.$(f.name)
24 }
25 }
26 return value_list
27}
28
29fn test_comptime_field_selector_read() {
30 assert comptime_field_selector_read[Foo]() == ['1', '2']
31}
32
33fn comptime_field_selector_write[T]() T {
34 mut t := T{}
35 $for f in T.fields {
36 $if f.typ is string {
37 t.$(f.name) = '1'
38 }
39 $if f.typ is int {
40 t.$(f.name) = 1
41 }
42 }
43 return t
44}
45
46fn test_comptime_field_selector_write() {
47 res := comptime_field_selector_write[Foo]()
48 assert res.immutable == 1
49 assert res.test == '1'
50 assert res.name == '1'
51}
52
53fn test_comptime_field_selector_write_enum() {
54 mut t := TestStruct{}
55
56 $for field in TestStruct.fields {
57 t.$(field.name) = 1
58 }
59 assert t.test == .one
60}
61
62struct Foo2 {
63 f Foo
64}
65
66fn nested_with_parentheses[T]() T {
67 mut t := T{}
68 $for f in T.fields {
69 $if f.typ is Foo {
70 t.$(f.name).test = '1'
71 }
72 }
73 return t
74}
75
76fn test_nested_with_parentheses() {
77 res := nested_with_parentheses[Foo2]()
78 assert res.f.test == '1'
79}
80