v2 / vlib / v / tests / comptime / comptime_default_value_test.v
64 lines · 53 sloc · 1.15 KB · d9c3ac5ce69cd5ece15bc6eb92c2a72c23f73e48
Raw
1module main
2
3struct Decoder {
4 json string
5}
6
7pub fn decode[T](val string) !T {
8 mut decoder := Decoder{
9 json: val
10 }
11
12 mut result := T{}
13 decoder.decode_value(mut &result)!
14 return result
15}
16
17fn (mut decoder Decoder) decode_value[T](mut val T) ! {
18 $if T is $array {
19 mut array_element := create_array_element(val)
20
21 decoder.decode_value(mut array_element)!
22 println(array_element)
23 dump(array_element)
24 assert &array_element != unsafe { nil }
25
26 val << array_element
27 } $else $if T is $map {
28 mut map_value := create_map_value(val)
29
30 decoder.decode_value(mut map_value)!
31 println(map_value)
32 dump(map_value)
33 assert &map_value != unsafe { nil }
34
35 val['key'] = map_value
36 }
37}
38
39fn create_array_element[T](array []T) T {
40 a := T{}
41 dump(a)
42 dump(a.str)
43 assert a.str != unsafe { nil }
44 return a
45}
46
47fn create_map_value[K, V](map_ map[K]V) V {
48 a := V{}
49 dump(a)
50 dump(a.str)
51 assert a.str != unsafe { nil }
52 return a
53}
54
55fn test_main() {
56 assert decode[[]string]('["1", "2", "3"]')! == ['']
57 assert decode[[]int]('[1, 2, 3]')! == [0]
58 assert decode[map[string]string]('{"val": "2"}')! == {
59 'key': ''
60 }
61 assert decode[map[string]int]('{"a": 1}')! == {
62 'key': 0
63 }
64}
65