Monday, 13 May 2019

Go language: Check for equality of two byte slices


Approach 1: Use bytes.Equal method

App.go
package main

import (
    "bytes"
    "fmt"
)

func main() {
    slice1 := []byte{2, 3, 5, 7}
    slice2 := []byte{1, 2, 3, 4}
    slice3 := []byte{2, 3, 5, 7}

    fmt.Printf("%v == %v : %v\n", slice1, slice2, bytes.Equal(slice1, slice2))
    fmt.Printf("%v == %v : %v\n", slice1, slice3, bytes.Equal(slice1, slice3))
    fmt.Printf("%v == %v : %v\n", slice2, slice3, bytes.Equal(slice2, slice3))
}

Output
[2 3 5 7] == [1 2 3 4] : false
[2 3 5 7] == [2 3 5 7] : true
[1 2 3 4] == [2 3 5 7] : false

Approach 2: Use reflect.DeepEqual


App.go
package main

import (
    "fmt"
    "reflect"
)

func main() {
    slice1 := []byte{2, 3, 5, 7}
    slice2 := []byte{1, 2, 3, 4}
    slice3 := []byte{2, 3, 5, 7}

    fmt.Printf("%v == %v : %v\n", slice1, slice2, reflect.DeepEqual(slice1, slice2))
    fmt.Printf("%v == %v : %v\n", slice1, slice3, reflect.DeepEqual(slice1, slice3))
    fmt.Printf("%v == %v : %v\n", slice2, slice3, reflect.DeepEqual(slice2, slice3))
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment