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