Checking the equality of two slices

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

How can I check if two slices are equal?

6条回答
  •  再見小時候
    2020-12-12 10:28

    If you have two []byte, compare them using bytes.Equal. The Golang documentation says:

    Equal returns a boolean reporting whether a and b are the same length and contain the same bytes. A nil argument is equivalent to an empty slice.

    Usage:

    package main
    
    import (
        "fmt"
        "bytes"
    )
    
    func main() {
        a := []byte {1,2,3}
        b := []byte {1,2,3}
        c := []byte {1,2,2}
    
        fmt.Println(bytes.Equal(a, b))
        fmt.Println(bytes.Equal(a, c))
    }
    

    This will print

    true
    false
    

提交回复
热议问题