Playing around at Go Generics draft design v2

·

1 min read

This is continue of previous blog

After some discussion, the playground is updated with generic with [type T] syntax

Using the example previous blog, here is the rewrite version

Contains function

Playground link

package main

import (
    "fmt"
)

func Contains[type 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[type T] struct {
    Arr []T
}

func NewMapable[type T](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)
}

I think with square bracket, it increases the readability.