v2 / vlib / v / tests / comptime / comptime_selector_mut_test.v
59 lines · 51 sloc · 879 bytes · 1d562915510c443d299994731f544df2ad072236
Raw
1struct Struct {
2mut:
3 a string
4 b int
5}
6
7fn decode_string[T](mut value T) {
8 value = 'gg'
9}
10
11fn decode_string_int[T](mut value T) {
12 value = 123
13}
14
15fn 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
28fn test_main() {
29 assert decode[Struct]() == Struct{
30 a: 'gg'
31 b: 123
32 }
33}
34
35struct OptionStruct {
36mut:
37 v ?int
38}
39
40fn decode_option_int[T](mut value T) {
41 $if T is int {
42 value = 42
43 }
44}
45
46fn 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
56fn test_comptime_option_payload_mut_generic() {
57 result := decode_option[OptionStruct]()
58 assert result.v? == 42
59}
60