func reverse(s []int) []int {
l := len(s)
rev := make([]int, l)
for i, item := range s {
rev[l-i-1] = item
}
return r
}
func reverse[T any](s []T) []T {
l := len(s)
rev := make([]T, l)
for i, item := range s {
rev[l-i-1] = item
}
return r
}
func reverse[T any](s []T) []T
Type Parameter
Type Constraint
reverse([]int{1, 2, 3, 4, 5})
reverse[int]([]int{1, 2, 3, 4, 5})
func print[T any](v T){
fmt.Println(v)
}
interface-based definition derived from usage patterns and some other conditions
separate definition for each combination of types passed at instantiation
Compiler
func ForEach[T any](s []T, f func(item T, i int , s []T)) {
for i, item := range s {
f(item,i,s)
}
}
func Keys[K comparable, V any](m map[K]V) []K {
// creating a slice of type K with length of map
key := make([]K, len(m))
i := 0
for k, _ := range m {
key[i] = k
i++
}
return key
}
// T is type parameter here, with any constraint
type MyStruct[T any] struct {
item T
}
// No new type parameter is allowed in struct methods
func (m *MyStruct[T]) Get() T {
return m.item
}
func (m *MyStruct[T]) Set(v T) {
m.item = v
}
type Pair[K, V any] struct {
Key K
Value V
}
func pairs[K comparable, V any](m map[K]V) []*Pair[K, V] {
result := make([]*Pair[K, V], len(m))
i := 0
for k, v := range m {
newPair := &Pair[K, V]{
Key: k,
Value: v,
}
result[i] = newPair
i++
}
return result
}
type Stringer interface {
String() string
}
func stringer[T Stringer](s T) string {
return s.String()
}
type Number interface {
int
}
type Number interface {
int | int8 | int16 | int32 | int64 | float32 | float64
}
func Max[T Number](x, y T) T {
if x > y {
return x
}
return y
}
func Max[T constraints.Ordered](x, y T) T {
if x > y {
return x
}
return y
}
type Number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~float32 | ~float64
}
// Type with underlying int
type Point int
func Max[T Number](x, y T) T {
if x > y {
return x
}
return y
}
func Max[T ~int | ~float32 | ~float64](x, y T) T {
if x > y {
return x
}
return y
}
type Integer interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
type Float interface {
~float32 | ~float64
}
type Number interface {
Integer | Float
}