Go

Generic Function with Type Parameters

admin by @admin ADMIN
Jun 16, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Go 1.18+ generics. `[T any]` is unconstrained; `[T comparable]` allows == and !=; custom constraints work too. The compiler infers T from arguments.
Go
Raw
package main

import "fmt"

// Reverse a slice of any element type
func Reverse[T any](s []T) []T {
    out := make([]T, len(s))
    for i, v := range s {
        out[len(s)-1-i] = v
    }
    return out
}

// First index of `target` in `s` — needs `comparable` to use ==
func IndexOf[T comparable](s []T, target T) int {
    for i, v := range s {
        if v == target {
            return i
        }
    }
    return -1
}

func main() {
    fmt.Println(Reverse([]int{1, 2, 3, 4}))           // [4 3 2 1]
    fmt.Println(Reverse([]string{"a", "b", "c"}))     // [c b a]
    fmt.Println(IndexOf([]string{"x", "y", "z"}, "y")) // 1
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.