Go语言学习: lo 包

go语言里的类似于 js 里的 lodash 的工具包
更新于: 2022-07-30 13:06:16

安装

go get github.com/samber/lo@v1

Filter

  • lo.Filter
func main() {
	numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	odds := lo.Filter(numbers, func(value int, index int) bool {
		return value%2 == 1
	})
	fmt.Println(odds)
}

ForEach

  • lo.ForEach
  • lo.Uniq
func main() {
	names := lo.Uniq[string]([]string{"Samuel", "Marc", "Samuel"})
	// foreach for names
	lo.ForEach(names, func(x string, index int) {
		fmt.Println(x, index)
	})
}

Map

  • lo.Map
  • func(x int64, _ int) 后面那个_,表示忽略,不能少,否则会编译报错
func main() {
	numbers := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	res := lo.Map[int64, string](numbers, func(x int64, _ int) string {
		return strconv.FormatInt(x*x, 10)
	})
	fmt.Println(res)
}

FilterMap

  • lo.FilterMap
  • 这是一个不错的实现,已经 借鉴@jswork/next-filter-map 中去啦
func main() {
	strs := []string{"cpu", "gpu", "mouse", "keyboard"}
	res := lo.FilterMap[string, string](strs, func(x string, _ int) (string, bool) {
		if strings.HasSuffix(x, "pu") {
			return x, true
		}
		return "", false
	})
	fmt.Println(res)
}

Reduce

func main() {
  vals := []int{1, 2, 3, 4}
  sum := lo.Reduce[int, int](vals, func(agg int, item int, _ int) int {
    return agg + item
  }, 0)
  fmt.Println(sum)
}

Times

  • 比较奇怪的设置,为啥必须要返回一个数组? T[],这个是源码里的
func main() {
	lo.Times[string](3, func(i int) string {
		fmt.Println("hello world")
		return ""
	})
}
func main() {
	lo.Times(3, func(i int) int {
		fmt.Println("hello world")
		return 0
	})
}

Uniq

  • lo.Uniq
  • lo.UniqBy
func main() {
	uniqValues := lo.Uniq[int]([]int{1, 2, 2, 1})
	fmt.Println(uniqValues)
}
func main() {
	uniqValues := lo.UniqBy[int, int]([]int{0, 1, 2, 3, 4, 5}, func(i int) int {
		return i % 3
	})
	fmt.Println(uniqValues)
}

GroupBy

func main() {
	groups := lo.GroupBy[int, int]([]int{0, 1, 2, 3, 4, 5}, func(i int) int {
		return i % 3
	})
	fmt.Println(groups)
}

参考