v2 / vlib / v / tests / generics / generics_method_test.v
93 lines · 78 sloc · 1.51 KB · 66d208b1775233ea3f04cdd78df71581edc32588
Raw
1struct Point {
2mut:
3 x int
4 y int
5}
6
7fn (mut p Point) translate[T](x T, y T) {
8 p.x += x
9 p.y += y
10}
11
12fn test_generic_method() {
13 mut pot := Point{}
14 pot.translate[int](1, 3)
15 pot.translate(1, 3)
16 println(pot)
17 assert pot == Point{
18 x: 2
19 y: 6
20 }
21}
22
23struct Person {
24mut:
25 name string
26}
27
28fn (mut p Person) show[T](name string, data T) string {
29 p.name = name
30 return 'name: ${p.name}, data: ${data}'
31}
32
33fn test_generic_method_with_fixed_arg_type() {
34 mut person := Person{}
35 res := person.show('bob', 10)
36 assert res == 'name: bob, data: 10'
37}
38
39struct Foo {}
40
41fn (v Foo) new[T]() T {
42 return T{}
43}
44
45fn test_generic_method_with_map_type() {
46 foo := Foo{}
47 mut a := foo.new[map[string]string]()
48 assert a == map[string]string{}
49 assert a.len == 0
50 a['a'] = 'a'
51 assert a.len == 1
52 assert a['a'] == 'a'
53}
54
55fn test_generic_method_with_array_type() {
56 foo := Foo{}
57 mut a := foo.new[[]string]()
58 assert a == []string{}
59 assert a.len == 0
60 a << 'a'
61 assert a.len == 1
62 assert a[0] == 'a'
63}
64
65fn test_generic_method_with_struct_type() {
66 foo := Foo{}
67 mut a := foo.new[Person]()
68 a.name = 'a'
69 assert a.name == 'a'
70}
71
72struct MethodArrayPtrTest {
73 a string
74}
75
76struct MethodArrayPtrDecoder {}
77
78fn (mut d MethodArrayPtrDecoder) decode_array[T](mut val []T) {
79 val << T{}
80}
81
82fn (mut d MethodArrayPtrDecoder) decode_value[T](mut val T) {
83 $if T is $array {
84 d.decode_array(mut val)
85 }
86}
87
88fn test_generic_method_array_of_ptr_generic_inference() {
89 mut d := MethodArrayPtrDecoder{}
90 mut a := []&MethodArrayPtrTest{}
91 d.decode_value(mut a)
92 assert a.len == 1
93}
94