Golang 如何比较struct、slice和map的相等性
在Golang中,使用“reflect.DeepEqual”函数来比较struct、slice和map的相等性。该函数用于检查两个元素是否是“深度相等”的。深度表示我们递归地比较对象的内容。两种不同类型的值永远不会深度相等。如果以下情况之一为真,则两个相同类型的值是深度相等的:
1. 当以下所有条件都为真时,Slice的值才是深度相等的:
- 它们都是nil或都不为nil。
- 它们的长度相同。
- 它们具有相同的初始条目(也就是说,“&x[0] == &y[0]”)或它们的对应元素(长度为“length”)是深度相等的。
2. 只有当它们的相应字段(即导出和非导出的字段)是深度相等的时,才认为Struct值是深度相等的。
3. 当以下每个条件都为真时,Map的值才是深度相等的:
- 它们都是nil或不为nil
- 它们的长度相同
- 它们对应的键具有深度相等的值
注意: 我们需要导入reflect包来使用DeepEqual。
语法:
func DeepEqual(x, y interface{}) bool
示例:
// Golang program to compare equality
// of struct, slice, and map
package main
import (
"fmt"
"reflect"
)
type structeq struct {
X int
Y string
Z []int
}
func main() {
s1 := structeq{X: 50,
Y: "GeeksforGeeks",
Z: []int{1, 2, 3},
}
s2 := structeq{X: 50,
Y: "GeeksforGeeks",
Z: []int{1, 2, 3},
}
// comparing struct
if reflect.DeepEqual(s1, s2) {
fmt.Println("Struct is equal")
} else {
fmt.Println("Struct is not equal")
}
slice1 := []int{1, 2, 3}
slice2 := []int{1, 2, 3, 4}
// comparing slice
if reflect.DeepEqual(slice1, slice2) {
fmt.Println("Slice is equal")
} else {
fmt.Println("Slice is not equal")
}
map1 := map[string]int{
"x": 10,
"y": 20,
"z": 30,
}
map2 := map[string]int{
"x": 10,
"y": 20,
"z": 30,
}
// comparing map
if reflect.DeepEqual(map1, map2) {
fmt.Println("Map is equal")
} else {
fmt.Println("Map is not equal")
}
}
输出:
Struct is equal
Slice is not equal
Map is equal
但是,“cmp.Equal”是比较struct更好的工具。我们需要导入“github.com/google/go-cmp/cmp”包才能使用它。以下是一个示例:
package main
import (
"fmt"
"github.com/google/go-cmp/cmp"
)
type structeq struct {
X int
Y string
Z []int
}
func main() {
s1 := structeq{X: 50,
Y: "GeeksforGeeks",
Z: []int{1, 2, 3},
}
s2 := structeq{X: 50,
Y: "GeeksforGeeks",
Z: []int{1, 2, 3},
}
// comparing struct
if cmp.Equal(s1, s2) {
fmt.Println("Struct is equal")
} else {
fmt.Println("Struct is not equal")
}
}
输出:
Struct is equal