출처: When to Use Generics in Go?. Introducing Go 1.18 generics and… | by Teiva Harsanyi | Medium
type Foo struct {}
func (f Foo) bar[T any](t T) {}
>>> methods cannot have type parameters
func getKeys[K comparable, V any](m map[K]V) []K {
var keys []K
for k, v := range m {
log.Printf("value %v of key is %v", v, k)
keys = append(keys, k)
}
return keys
}
type Node[T any] struct {
Val T
next *Node[T]
}
func (n *Node[T]) Add(next *Node[T]) {
n.next = next
}
type Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
type sliceFn[T any] struct {
s []T
compare func(T, T) bool
}
func (s sliceFn[T]) Len() int { return len(s.s) }
func (s sliceFn[T]) Less(i, k int) {return s.compare(s.s[i], s.s[j])}
func (s sliceFn[T]) Swap(i, j int) {s.s[i], s.s[j] = s.s[j], s.s[i] }
func foo[T io.Writer](w T) {
_, _ = w.Write([]byte("hello"))
}
func foo(w io.Writer) {
w.Write([]byte("hello"))
}