为什么在Golang中[...] int {0} vs make([] int,1,1)的DeepEqual失败?还有其他选择吗?

时间:2017-11-30 18:09:27

标签: go

我不明白为什么DeepEqual在这种情况下会失败?

是否有内置golang替代方案而不迭代每个值。

package main

import (
    "fmt"
    "reflect"
)

func main() {
    a1 := [...]int{0}
    b1 := make([]int, 1, 1)
    fmt.Printf("Equal: %t %v %v\n", reflect.DeepEqual(a1, b1),a1,b1)

}

https://play.golang.org/p/lqU3nBq6B3

1 个答案:

答案 0 :(得分:5)

它们甚至不是同一类型:

a1 := [...]int{0}       // *array*, equivalent to [1]int{0}
b1 := make([]int, 1, 1) // *slice*, equivalent to []int{0}

// Equal: false - because they're different types!
fmt.Printf("Equal: %t (types: %T vs %T)\n", reflect.DeepEqual(a1, b1), a1, b1)
// But, if we take a slice of the array, they're comparable:
fmt.Printf("Equal: %t (types: %T vs %T)\n", reflect.DeepEqual(a1[:], b1), a1[:], b1)

游乐场示范:https://play.golang.org/p/B77iKS8gQd

声明在the spec section on composite literals中解释。 the Go tourthe spec section on slice expressions涵盖了切片数组。