Source file
test/typeparam/boundmethod.go
1
2
3
4
5
6
7
8
9
10
11 package main
12
13 import (
14 "fmt"
15 "reflect"
16 "strconv"
17 )
18
19 type myint int
20
21
22 func (m myint) String() string {
23 return strconv.Itoa(int(m))
24 }
25
26 type Stringer interface {
27 String() string
28 }
29
30 func stringify[T Stringer](s []T) (ret []string) {
31 for _, v := range s {
32
33 x1 := v.String()
34
35
36 v1 := Stringer(v)
37 x2 := v1.String()
38
39
40 f1 := T.String
41 x3 := f1(v)
42
43
44 f2 := func(v1 T) string {
45 return Stringer(v1).String()
46 }
47 x4 := f2(v)
48
49 if x1 != x2 || x2 != x3 || x3 != x4 {
50 panic(fmt.Sprintf("Mismatched values %v, %v, %v, %v\n", x1, x2, x3, x4))
51 }
52
53 ret = append(ret, v.String())
54 }
55 return ret
56 }
57
58 type Ints interface {
59 ~int32 | ~int
60 }
61
62
63
64
65
66
67
68
69
70 type StringStruct[T Ints] struct {
71 f T
72 }
73
74 func (m StringStruct[T]) String() string {
75 return strconv.Itoa(int(m.f))
76 }
77
78 func main() {
79 x := []myint{myint(1), myint(2), myint(3)}
80
81
82 got := stringify(x)
83 want := []string{"1", "2", "3"}
84 if !reflect.DeepEqual(got, want) {
85 panic(fmt.Sprintf("got %s, want %s", got, want))
86 }
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101 x3 := []StringStruct[myint]{StringStruct[myint]{f: 11}, StringStruct[myint]{f: 10}, StringStruct[myint]{f: 9}}
102
103 got3 := stringify(x3)
104 want3 := []string{"11", "10", "9"}
105 if !reflect.DeepEqual(got3, want3) {
106 panic(fmt.Sprintf("got %s, want %s", got3, want3))
107 }
108 }
109
View as plain text