v2 / vlib / v / tests / comptime / comptime_default_value_indexexpr_test.v
56 lines · 43 sloc · 1.0 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.unaliased_typ is $array {
19 mut array_element := create_array_element(val)
20
21 decoder.decode_value(mut array_element)!
22
23 val << array_element
24
25 assert val.len == 1
26 assert val[0] == array_element
27 } $else $if T.unaliased_typ is $map {
28 mut map_value := create_map_value(val)
29
30 decoder.decode_value(mut map_value)!
31
32 val['key'] = map_value
33
34 assert val.len == 1
35 assert val['key'] == map_value
36 }
37}
38
39fn create_array_element[T](array []T) T {
40 return T{}
41}
42
43fn create_map_value[K, V](map_ map[K]V) V {
44 return V{}
45}
46
47fn test_main() {
48 assert decode[[]int]('[1, 2, 3]')! == [0]
49 assert decode[[]string]('["1", "2", "3"]')! == ['']
50 assert decode[map[string]int]('{"a": 1}')! == {
51 'key': 0
52 }
53 assert decode[map[string]string]('{"val": "2"}')! == {
54 'key': ''
55 }
56}
57