Go 1.18 will be a significant release and contains a lot of new features. One of them is generics which you can experiment yourself with using either the playground or gotip.
Examples:
Go 1.18 will be a significant release and contains a lot of new features. One of them is generics which you can experiment yourself with using either the playground or gotip.
Examples:
// Go 1.17 | |
func ValToPtr(val interface{}) *interface{} { | |
return &val | |
} | |
strPtr := ValToPtr("Foo") | |
integerPtr := ValToPtr(1) | |
// Go 1.18 | |
func ValToPtr[T any](val T) *T { | |
return &val | |
} | |
strPtr := ValToPtr("Foo") | |
integerPtr := ValToPtr(1) |
// Go 1.17 | |
func MaxInt(input []int) (max int) { | |
for _, v := range input { | |
if v > max { | |
max = v | |
} | |
} | |
return max | |
} | |
func MaxFloat32(input []float32) (max float32) { | |
for _, v := range input { | |
if v > max { | |
max = v | |
} | |
} | |
return max | |
} | |
maxFloat32 := MaxFloat32([]float32{1.2, 8.2, 4.2}) | |
maxInt := MaxInt([]int{1, 8, 4}) | |
// Go 1.18 | |
func Max[T constraints.Ordered](input []T) (max T) { | |
for _, v := range input { | |
if v > max { | |
max = v | |
} | |
} | |
return max | |
} | |
maxFloat32 := Max([]float32{1.2, 8.2, 4.2}) | |
maxInt := Max([]int{1, 8, 4}) |
// Go 1.17 | |
func DoStuffForStr(val string) { | |
// Do stuff | |
} | |
func DoStuffForInt(val int) { | |
// Do stuff | |
} | |
DoStuffForStr("1") | |
DoStuffForInt(1) | |
// Go 1.18 | |
type CustomConstraint interface { | |
type string, int | |
} | |
func DoStuff[T CustomConstraint](val T) { | |
// Do stuff | |
} | |
DoStuff("1") | |
DoStuff(1) |
// Go 1.17 | |
type StrCollection []string | |
func (c StrCollection) Print() { | |
// Do stuff | |
} | |
type IntCollection []int | |
func (c IntCollection) Print() { | |
// Do stuff | |
} | |
coll1 := StrCollection{"1", "2", "3"} | |
coll1.Print() | |
coll2 := IntCollection{1, 2, 3} | |
coll2.Print() | |
// Go 1.18 | |
type CustomConstraint interface { | |
type string, int | |
} | |
type Collection[T CustomConstraint] []T | |
func (c Collection[T]) Print() { | |
// Do stuff | |
} | |
coll1 := Collection[T string]{"1", "2", "3"} | |
coll1.Print() | |
coll2 := Collection[T int]{1, 2, 3} | |
coll2.Print() |