Go Generics draft design Final

ยท

2 min read

This is continue of previous blog

The syntax now is settled with [T any] syntax, without type keyword, where any indicates that there are no constraints.

Using the example previous blog, here is the rewrite version without type

Contains function

Playground link

package main

import (
    "fmt"
)

func Contains[T comparable](col []T, item T) bool {
    for _, e := range col {
        if e == item {
            return true
        }
    }
    return false
}

func main() {
    fmt.Println(Contains([]string{"coffee", "tea"}, "coffee"))
    fmt.Println(Contains([]int{1, 2, 3}, 11))
    fmt.Println(Contains([]int{1, 2, 3}, 1))
}

Mappable function

Playground link

package main

import "fmt"

type Mapable[T any] struct {
    Arr []T
}

func NewMapable[T any](col []T) Mapable[T] {
    return Mapable[T]{Arr: col}
}

func (m Mapable[T]) Map(fn func(T) T) Mapable[T] {
    var newCol []T
    for _, item := range m.Arr {
        newCol = append(newCol, fn(item))
    }
    return NewMapable(newCol)
}

func main() {

    mapable := NewMapable([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
    res := mapable.
        Map(func(s int) int {
            return s * 10
        }). // {[10 20 30 40 50 60 70 80 90 100]}
        Map(func(s int) int {
            return s + 20
        }) // {[30 40 50 60 70 80 90 100 110 120]}

    fmt.Println(res)
}

Max function

Let's have more constraint on the type, instead of just any. With the Min function example on the playground, we refactor to Max function

Playground link

package main

import (
    "fmt"
)

type numeric interface {
    type int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64
}

func max[T numeric](a, b T) T {
    if a > b {
        return a
    }
    return b
}

func main() {
    fmt.Println(max(42, 84))
    fmt.Println(max(3.14159, 2.7182))
}

Generics most likely will release at Q3 of 2021. It will unlock a lot of possibilities.

That's all for the quick sharing. Thanks for reading ๐Ÿป

Did you find this article valuable?

Support Wei Lun by becoming a sponsor. Any amount is appreciated!