DEV Community

Cover image for Generics In Golang
VibhorDubey
VibhorDubey

Posted on

Generics In Golang

Generics in Go got introduced in release 1.18.

What are generics?

Generics is a mechanism through which we can pass any type of value in a function.

What were the issues prior to Go version 1.18?

package main

import "fmt"

func main() {
    stringObject := "Hello"
    floatObject := 3.14
    intObject := 7

    assertType(stringObject)
    assertType(intObject)
    assertType(floatObject)
}

func assertType(object interface{}) {
    switch object.(type) {
    case string:
        fmt.Println("Received Type:", object.(string))
    case int:
        fmt.Println("Received Type:", object.(int))
    default:
        fmt.Println("Unknown Type")
    }
}
Enter fullscreen mode Exit fullscreen mode

So, every time we need to infer the type if we infer it with wrong datatype it will result into panic. Let's see another simple example.

package main

import "fmt"

func main() {
    stringObject := "Hello"
    printValue(stringObject)
}

func printValue(object interface{}) {
    fmt.Println(object.(int))
}
Enter fullscreen mode Exit fullscreen mode

Here, we're trying to infer the string as int so it will result in a panic. So if we don't use the correct type it will cause panic in our program.

3. Genrics Code Example?

A. Any
Let's see our first example. Where we'll pass any value in function be it array, int, string.

package main

import (
    "fmt"
)

func assertType(T any) {
    fmt.Println(T)
}
func assertTypeArray[T any](arrayObject []T) []T {
    for i := range arrayObject {
        fmt.Println(i)
    }
    return arrayObject
}
func main() {
    assertType("Hello")
    assertType(12.32)

    array := []int{1, 2, 3}
    arrayObject := assertTypeArray(array)
    fmt.Println(arrayObject)
}
Enter fullscreen mode Exit fullscreen mode

B. Predefined constraints.

We can define the datatypes in interface like Integer, Float then embed inside Number interface. Using predefined constraint we can restrict the input.

package main

import (
    "fmt"
)

type Integer interface {
    ~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Float interface {
    ~float32 | ~float64
}

type Number interface {
    Integer | Float
}

func Min[T Number](x, y T) T {
    if x < y {
        return x
    }
    return y
}

type IntType int64

func main() {
    x, y := 1, 3
    a, b := 1.1, 4.5
    k, v := IntType(-12344), IntType(12)
    fmt.Println(Min(x, y))
    fmt.Println(Min(a, b))
    fmt.Println(Min(k, v))
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)