Checking the equality of two slices

后端 未结 6 1202
天命终不由人
天命终不由人 2020-12-12 10:05

How can I check if two slices are equal?

6条回答
  •  难免孤独
    2020-12-12 10:45

    You need to loop over each of the elements in the slice and test. Equality for slices is not defined. However, there is a bytes.Equal function if you are comparing values of type []byte.

    func testEq(a, b []Type) 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
    }
    

提交回复
热议问题