Quidest?

Generic type parameters in Go

· Lorenzo Drumond

Go functions can be written to work on multiple types using type parameters. The type parameters of a function appear between brackets, before the function’s argument:

1func Index[T comparable](s []T, x T) int

This declaration means that s is a slice of any type T that fulfills the built-in constraint comparable. x is also a value of the same type.

comparable is a useful constraint that makes it possible to use the == and != operators on values of the same type. In this example, we use it to compare a value to all slice elements until a match is found. This Index function works for any type that supports comparison.

 1package main
 2
 3import "fmt"
 4
 5// Index returns the index of x in s, or -1 if not found.
 6func Index[T comparable](s []T, x T) int {
 7  for i, v := range s {
 8    // v and x are type T, which has the comparable constraint
 9    if v == x {
10      return i
11    }
12  }
13  return -1
14}
15
16func main() {
17  // Index works on a slice of ints
18  si := []int{10, 20, 15, -10}
19  fmt.Println(Index(si, 15))
20
21  // Index also works on a slice of strings
22  ss := []string{"foo", "bar", "baz"}
23  fmt.Println(Index(ss, "hello"))
24}
25
26// Output:
27// 2
28// -1

References

Next -> generic-types-in-go

#type #generics #parameters #golang #type_theory #comparable