`slices.Equal` 是 Go 1.21 引入的内置函数,用于比较两个切片是否相等。它能大大简化切片比较的代码。
让我们看一下具体用法:
```go // 传统方式 func equalSlices(a, b []int) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true }
// 使用 slices.Equal import "slices"
// 一行代码就能完成比较 result := slices.Equal(a, b) ```
可以替换的主要场景:
1. 基本类型切片比较: ```go // 替换前 func compareInts(a, b []int) bool { if len(a) != len(b) { return false } for i, v := range a { if v != b[i] { return false } } return true }
// 替换后 slices.Equal(a, b) ```
2. 字符串切片比较: ```go // 替换前 func compareStrings(a, b []string) bool { if len(a) != len(b) { return false } for i, v := range a { if v != b[i] { return false } } return true }
"Expanse, a Palo Alto Networks company, searches across the global IPv4 space multiple times per day to identify customers' presences on the Internet. If you would like to be excluded from our scans, please send IP addresses/domains to: scaninfo@paloaltonetworks.com"