随着Go 1.21的发布,将有两个令人兴奋的包被引入到核心库中,这两个包专注于操作maps和提供比较功能。让我们仔细看看这些包: 1. maps 包maps 包为处理maps提供实用工具,使克隆、复制、删除和比较map条目变得更加简单和高效。
函数 m := map[string]int{"one": 1, "two": 2} cloned := maps.Clone(m) fmt.Println(cloned) // Output: map[one:1 two:2]
dst := map[string]int{"one": 1} src := map[string]int{"two": 2} maps.Copy(dst, src) // dst is now {"one": 1, "two": 2} fmt.Printf("%#v\n", dst)
m := map[string]int{"one": 1, "two": 2} maps.DeleteFunc(m, func(k string, v int) bool { return v == 2 }) fmt.Println(m) // Output: map[one:1]
m1 := map[string]int{"one": 1, "two": 2} m2 := map[string]int{"one": 1, "two": 2} equal := maps.Equal(m1, m2) // true fmt.Println(equal)
2. cmp 包cmp 包定义了用于比较有序类型的函数和类型,包括整数、浮点数和字符串。该包提供了一种一致的方式来比较值,包括浮点类型的 NaN 值。
函数 result := cmp.Compare(5, 10) // -1 fmt.Println(result) result = cmp.Compare(10, 5) // 1 fmt.Println(result) result = cmp.Compare(5, 5) // 0 fmt.Println(result)
isLess := cmp.Less(5, 10) // true fmt.Println(isLess) isLess = cmp.Less(10, 5) // false fmt.Println(isLess) isLess = cmp.Less(10, 10) // false fmt.Println(isLess)
类型 func Min[T cmp.Ordered](a, b T) T { if cmp.Less(a, b) { return a } return b }
func main() { minInt := Min(3, 5) // minInt is 3 minString := Min("a", "b") // minString is "a"
fmt.Println(minInt, minString) }
结论在 Go 中引入 maps 和 cmp 包代表了增强该语言核心功能的重要一步。有了这些添加,开发者现在可以轻松地操作和比较映射和有序类型,进一步简化他们的代码。通过将常见操作抽象到这些核心包中,Go 继续追求开发体验中的效率、清晰性和稳健性。
|