| 1 | struct Point { |
| 2 | mut: |
| 3 | x int |
| 4 | y int |
| 5 | } |
| 6 | |
| 7 | fn (mut p Point) translate[T](x T, y T) { |
| 8 | p.x += x |
| 9 | p.y += y |
| 10 | } |
| 11 | |
| 12 | fn 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 | |
| 23 | struct Person { |
| 24 | mut: |
| 25 | name string |
| 26 | } |
| 27 | |
| 28 | fn (mut p Person) show[T](name string, data T) string { |
| 29 | p.name = name |
| 30 | return 'name: ${p.name}, data: ${data}' |
| 31 | } |
| 32 | |
| 33 | fn 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 | |
| 39 | struct Foo {} |
| 40 | |
| 41 | fn (v Foo) new[T]() T { |
| 42 | return T{} |
| 43 | } |
| 44 | |
| 45 | fn 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 | |
| 55 | fn 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 | |
| 65 | fn 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 | |
| 72 | struct MethodArrayPtrTest { |
| 73 | a string |
| 74 | } |
| 75 | |
| 76 | struct MethodArrayPtrDecoder {} |
| 77 | |
| 78 | fn (mut d MethodArrayPtrDecoder) decode_array[T](mut val []T) { |
| 79 | val << T{} |
| 80 | } |
| 81 | |
| 82 | fn (mut d MethodArrayPtrDecoder) decode_value[T](mut val T) { |
| 83 | $if T is $array { |
| 84 | d.decode_array(mut val) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | fn 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 | |