100-go-mistakes/2-code-project-organization/9-generics/main.go
2021-12-27 15:56:17 +01:00

54 lines
No EOL
982 B
Go

package main
import "fmt"
func getKeys(m any) ([]any, error) {
switch t := m.(type) {
default:
return nil, fmt.Errorf("unknown type: %T", t)
case map[string]int:
var keys []any
for k := range t {
keys = append(keys, k)
}
return keys, nil
case map[int]string:
// ...
}
return nil, nil
}
func getKeysGenerics[K comparable, V any](m map[K]V) []K {
var keys []K
for k := range m {
keys = append(keys, k)
}
return keys
}
type customConstraint interface {
~int | ~string <1>
}
func getKeysWithConstraing[K customConstraint, V any](m map[K]V) []K {
return nil
}
type Node[T any] struct {
Val T
next *Node[T]
}
func (n *Node[T]) Add(next *Node[T]) {
n.next = next
}
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, j int) bool { 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] }