Generic Functions in Go

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

Leave a Comment