https://stackoverflow.com/questions/15311969/checking-the-equality-of-two-slices

问题

已知 ==!= 不可用的情况下怎么判断两个切片相等?

package main

import "fmt"

func main() {
    s1 := []int{1, 2}
    s2 := []int{1, 2}
    fmt.Println(s1 == s2)
}

这段代码会编译失败:

invalid operation: s1 == s2 (slice can only be compared to nil)

回答

你需要 reflect.DeepEqual()

DeepEqual is a recursive relaxation of Go’s == operator.

DeepEqual reports whether x and y are “deeply equal,” defined as follows. Two values of identical type are deeply equal if one of the following cases applies. Values of distinct types are never deeply equal.

Array values are deeply equal when their corresponding elements are deeply equal.

Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.

Func values are deeply equal if both are nil; otherwise they are not deeply equal.

Interface values are deeply equal if they hold deeply equal concrete values.

Map values are deeply equal if they are the same map object or if they have the same length and their corresponding keys (matched using Go equality) map to deeply equal values.

Pointer values are deeply equal if they are equal using Go’s == operator or if they point to deeply equal values.

Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal.

Other values – numbers, bools, strings, and channels – are deeply equal if they are equal using Go’s == operator.

译:

DeepEqual 是 Go 中递归展开的 == 运算符。

DeepEqual 判断 x 与 y 是否“深度相等”,定义如下面所示。两个相同类型的值当满足下列条件中的其一时深度相等,而两个类型不同的值永远不会深度相等。

当数组中的每个元素和另一数组中对应元素深度相等时,这两个数组深度相等。

当结构体中所有导出的和未导出的字段都对应深度相等时,结构体深度相等。

函数变量仅在都为 nil 时深度相等,否则不深度相等。

接口值包含深度相等的值时深度相等。

当 map 值指向同一个底层对象时,或它们有相同的长度且对应的键(根据 Go 相等性配对)的值深度相等时,这两个 map 深度相等。

指针值在 == 运算符判断相等或它们指向深度相等的值时深度相等。

切片值当满足以下所有条件时深度相等:它们都是 nil 或都不是 nil;有相同的长度;它们指向同一个底层数组位置(根据 &x[0] == &y[0] 判断),或它们对应位置的元素(根据长度)都深度相等。需要注意的是,一个非 nil 的空切片和一个 nil 切片(比如 []byte{} 和 []byte{nil})不是深度相等的。

其他值——数字、布尔型、字符串、通道——当 == 运算符判断相等时即深度相等。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注