1
2
3
4
5
6
7
8
9 package main
10
11 import (
12 "fmt"
13 "reflect"
14 "strconv"
15 )
16
17
18 type Stringer interface {
19 String() string
20 }
21
22 func stringify[T Stringer](s []T) (ret []string) {
23 for _, v := range s {
24 ret = append(ret, v.String())
25 }
26 return ret
27 }
28
29 type myint int
30
31 func (i myint) String() string {
32 return strconv.Itoa(int(i))
33 }
34
35
36 type Stringer2 interface {
37 CanBeStringer2() int
38 SubStringer2
39 }
40
41 type SubStringer2 interface {
42 CanBeSubStringer2() int
43 String() string
44 }
45
46 func stringify2[T Stringer2](s []T) (ret []string) {
47 for _, v := range s {
48 ret = append(ret, v.String())
49 }
50 return ret
51 }
52
53 func (myint) CanBeStringer2() int {
54 return 0
55 }
56
57 func (myint) CanBeSubStringer2() int {
58 return 0
59 }
60
61
62 func stringify3[T Stringer](s []T) (ret []string) {
63 for _, v := range s {
64 f := v.String
65 ret = append(ret, f())
66 }
67 return ret
68 }
69
70 func main() {
71 x := []myint{myint(1), myint(2), myint(3)}
72
73 got := stringify(x)
74 want := []string{"1", "2", "3"}
75 if !reflect.DeepEqual(got, want) {
76 panic(fmt.Sprintf("got %s, want %s", got, want))
77 }
78
79 got = stringify2(x)
80 if !reflect.DeepEqual(got, want) {
81 panic(fmt.Sprintf("got %s, want %s", got, want))
82 }
83
84 got = stringify3(x)
85 if !reflect.DeepEqual(got, want) {
86 panic(fmt.Sprintf("got %s, want %s", got, want))
87 }
88 }
89
View as plain text