下面由golang教程欄目給大家介紹golang中判斷兩個slice是否相等與判斷值下的 數(shù)組是否相等,希望對需要的朋友有所幫助!
在golang中我們可以輕松地通過==
來判斷兩個數(shù)組(array)是否相等,但遺憾的是slice并沒有相關(guān)的運算符,當(dāng)需要判斷兩個slice是否相等時我們只能另尋捷徑了。
slice相等的定義
我們選擇最常見的需求,也就是當(dāng)兩個slice的類型和長度相同,且相等下標(biāo)的值也是相等的,比如:
a := []int{1, 2, 3}b := []int{1, 2, 3}c := []int{1, 2}d := []int{1, 3, 2}
上述代碼中a
和b
是相等的,c
因為長度和a
不同所以不相等,d
因為元素的排列順序和a
不同所以也不相等。
判斷兩個[]byte是否相等
為什么要單獨將[]byte列舉出來呢?
因為標(biāo)準(zhǔn)庫提供了優(yōu)化的比較方案,不再需要我們造輪子了:
package mainimport ( "bytes" "fmt")func main() { a := []byte{0, 1, 3, 2} b := []byte{0, 1, 3, 2} c := []byte{1, 1, 3, 2} fmt.Println(bytes.Equal(a, b)) fmt.Println(bytes.Equal(a, c))}
使用reflect判斷slice(數(shù)組)是否相等
在判斷類型不是[]byte的slice時,我們還可以借助reflect.DeepEqual
,它用于深度比較兩個對象包括它們內(nèi)部包含的元素是否都相等:
func DeepEqual(x, y interface{}) bool
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.
…
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.
這段話的意思不難理解,和我們在本文最開始時討論的如何確定slice相等的原則是一樣的,只不過它借助了一點運行時的“黑魔法”。
看例子:
package mainimport ( "fmt" "reflect")func main() { a := []int{1, 2, 3, 4} b := []int{1, 3, 2, 4} c := []int{1, 2, 3, 4} fmt.Println(reflect.DeepEqual(a, b)) fmt.Println(reflect.DeepEqual(a, c))}
手寫判斷
在golang中使用reflect通常需要付出性能代價,如果我們確定了slice的類型,那么自己實現(xiàn)slice的相等判斷相對來說也不是那么麻煩:
func testEq(a, b []int) bool { // If one is nil, the other must also be nil. if (a == nil) != (b == nil) { return false; } if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true}
測試代碼:
package main import "fmt" func main() { a := []int{1, 2, 3, 4} b := []int{1, 3, 2, 4} c := []int{1, 2, 3, 4} fmt.Println(testEq(a, b)) fmt.Println(testEq(a, c))}