Playing around at Go Generics draft design
Recently Go has released an experimentation tool for generics. Here is my quick attempts.
Contains function
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")) // true
fmt.Println(Contains([]int{1, 2, 3}, 11)) // false
fmt.Println(Contains([]int{1, 2, 3}, 1)) // true
}
Mappable function
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)
}
Hashtable
I wonder why choose ()
over <>
, a bit too much parenthesis in my opinion. Let's discuss about it.