Sobes.tech
Junior — Middle

Can you give examples of methods for implementing universal or generic code?

sobes.tech AI

Answer from AI

In Go (Golang), generic or universal code can be implemented using generics, which appeared starting from version 1.18. They allow writing functions and types that work with different data types without duplicating code.

Example of a generic function to find the maximum in a slice:

package main

import (
    "fmt"
    "golang.org/x/exp/constraints"
)

func Max[T constraints.Ordered](slice []T) T {
    max := slice[0]
    for _, v := range slice[1:] {
        if v > max {
            max = v
        }
    }
    return max
}

func main() {
    ints := []int{1, 5, 3}
    floats := []float64{2.5, 3.7, 1.4}

    fmt.Println(Max(ints))   // 5
    fmt.Println(Max(floats)) // 3.7
}

Other methods of universality include using interfaces, but generics provide more strict typing and convenience.

Can you give examples of methods for implementing… - sobes.tech