Skip to content

Instantly share code, notes, and snippets.

@dannyskoog
Last active December 7, 2021 19:08
Show Gist options
  • Save dannyskoog/60624d0f0292dd870510c60a0bd18b9d to your computer and use it in GitHub Desktop.
Save dannyskoog/60624d0f0292dd870510c60a0bd18b9d to your computer and use it in GitHub Desktop.
Go 1.18 - Generics
// 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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment