v2 / vlib / v / tests / generics / generic_fn_param_test.v
42 lines · 33 sloc · 757 bytes · b1bd4c4a1c8501b21d2065eae071062652c3f0d5
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 } $else $if T is $map {
23 mut map_value := create_map_value(val)
24
25 decoder.decode_value(mut map_value)!
26 }
27}
28
29fn create_array_element[T](array []T) T {
30 return T{}
31}
32
33fn create_map_value[K, V](map_ map[K]V) V {
34 return V{}
35}
36
37fn test_main() {
38 decode[[]int]('[1, 2, 3]')!
39 decode[[]string]('["1", "2", "3"]')!
40 decode[map[string]int]('{"a": 1}')!
41 decode[map[string]string]('{"val": "2"}')!
42}
43