Syntax

The basic syntax for writing generic code can be explained by taking a look at an example from the previous page:

  1. // Sum returns the sum of the provided arguments.
  2. func Sum(args ...int) int {
  3. var sum int
  4. for i := 0; i < len(args); i++ {
  5. sum += args[i]
  6. }
  7. return sum
  8. }

The above function:

  • takes zero to many int arguments
  • returns an int value

In fact, there is no type a part of the function signature or body that is not int. So one way to rewrite the above function generically would be to let T represent int (Go playground):

  1. // Sum returns the sum of the provided arguments.
  2. func Sum[T int](args ...T) T {
  3. var sum T
  4. for i := 0; i < len(args); i++ {
  5. sum += args[i]
  6. }
  7. return sum
  8. }

The above function’s name is suceeded by [T int], the basic form of the syntax for expressing generics in Go:

  • the [] brackets are always used to define the generics
  • the most basic pattern is [<ID> <CONSTRAINT>] where:
    • <ID>: is the symbol used to represent the generic type
    • <CONSTRAINT>: is the constraint that indicates which concrete types can be used

In the above example the generic type T is constrainted to int, which means it is not possible to call Sum[T int](...T) T with a list of int64 values (Golang playground):

  1. func main() {
  2. fmt.Println(Sum([]int64{1, 2, 3}...))
  3. }

Trying to run the above example will produce the following compiler error:

  1. ./prog.go:17:17: int64 does not implement int

The next page will review how to rewrite the above function so that more than one type can satisfy its constraints.


Next: Constraints