Go – Implementing Generic Functions

genericsgointerface

I'm in the process of learning Go and the documentation and interactive lessons say that an empty interface can hold any type, as it requires no additionally implemented methods.

So for an example:

func describe(i interface{}) {
    fmt.Printf("Type: %T | Value: %v\n", i, i)
}

…would print out…

"Type: int | Value: 5" // for i := 5
"Type: string | Value: test" // for i := "test"
... etc

So I guess my question is if this is Go's way of implementing generic functions or if there is another, more suitable, way of doing them.

Best Answer

As of Go 1.18 you can write a generic function Print as below:

package main

import (
    "fmt"
)

// T can be any type
func Print[T any](s []T) {
    for _, v := range s {
        fmt.Print(v)
    }
}

func main() {
    // Passing list of string works
    Print([]string{"Hello, ", "world\n"})

    // You can pass a list of int to the same function as well
    Print([]int{1, 2})
}

Output:

Hello, world
12