Go 1.18 is released today! Download the latest version here
Let's try a library called "lo" for common generics operations. The lo library is similar to Javascript's lodash.
Example:
package main
import (
"fmt"
"github.com/samber/lo"
)
func main() {
nums := []int{1, 2, 3}
lo.ForEach(nums, func(t int, i int) {
fmt.Println(t)
})
doubles := lo.Map(nums, func(num int, _ int) int {
return num * 2
})
fmt.Println("doubles:", doubles)
odds := lo.Filter(nums, func(v int, _ int) bool {
return v%2 != 0
})
fmt.Println("odds:", odds)
lo.Shuffle(nums)
fmt.Println("randomed:", nums)
reversed := lo.Reverse(nums)
fmt.Println("reversed:", reversed)
if idx := lo.IndexOf(nums, 3); idx != -1 {
fmt.Println("Found 3")
} else {
fmt.Println("Not found 3")
}
ele, found := lo.Find(nums, func(v int) bool {
return v == 2
})
fmt.Println("Found:", found, "Element:", ele)
arr := lo.Range(5)
fmt.Println("array:", arr)
// get map.keys
m := map[string]string{
"name": "John",
"score": "A",
}
fmt.Println(lo.Keys(m))
fmt.Println(lo.Values(m))
for _, item := range lo.Entries(m) {
fmt.Println("Key:", item.Key, "=>", "Value:", item.Value)
}
}
Run it:
$ go run main.go
1
2
3
doubles: [2 4 6]
odds: [1 3]
randomed: [1 3 2]
reversed: [2 3 1]
Found 3
Found: true Element: 2
array: [0 1 2 3 4]
[name score]
[John A]
Key: name => Value: John
Key: score => Value: A
Top comments (1)
Yeah this is a great library! Thanks for the post!