In Go 1.18, we get access to Genrics. Huzzah!

Here’s an basic example of how to use them:

package main

import (
	"fmt"
)

func PrintAge[age float32 | int64](myAge age) {
	fmt.Printf("age: %s \t type: %T\n", myAge, myAge)
}

func main() {
	var age1 float32 = 30.5
	var age2 int64 = 32

	PrintAge(age1)
	PrintAge(age2)
}

Running the above program gives us the below output. You can see that it happily accepted the float32 and int64 values without issue.

age: %!s(float32=30.5)	type: float32
age: %!s(int64=32)		type: int64

This saves us from having to either (a) define a separate PrintAge function for every type of number we want to accept or (b) writing the PrintAge to accept type interface{} which would then accept types we don’t want to accept (and having to mess with type assertions and all that).

If we are going to write multiple functions which use the same generics, you can define them as an interface type like so:

package main

import "fmt"

type Number interface {
	float32 | int64
}

func PrintAge[N Number](myAge N) {
	fmt.Printf("age: %s \t type: %T\n", myAge, myAge)
}

func main() {
	var age1 float32 = 30.5
	var age2 int64 = 32

	PrintAge(age1)
	PrintAge(age2)
}

Neat.