swappy
swappy

Reputation: 135

Unable to compare byte slices

I am trying to write a unit test case, where I'm using reflect.DeepEqual to compare computed and expected results. One of the entries in the struct is a byte slice and DeepEqual keeps on failing it.

Sample Code https://goplay.space/#OcAPkK-EqDX

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var a = []byte("qwedsa")
    var b [6]byte
    copy(b[:], a)
    fmt.Println(reflect.DeepEqual(a, b), len(a), len(b), cap(a), cap(b))
}

Upvotes: 0

Views: 2208

Answers (3)

Gopher
Gopher

Reputation: 751

Based on the suggestions you have to convert your byte array to byte slice and use bytes.Equal .Here is the implementation of the same:

package main

import (
    "bytes"
    "fmt"
)

func main() {
    var a = []byte("qwedsa")
    var b [6]byte

    sliceb := b[:]
    copy(sliceb, a)
    fmt.Println(bytes.Equal(a, sliceb))
}

Output:

true

Upvotes: 0

nipuna
nipuna

Reputation: 4095

reflect.DeepEqual(a, b) returns false because you are comparing two types.

var a = []byte("qwedsa") //here a is a slice with length 6

var b [6]byte //here b is a array with length 6

You can use different options to Do this as mentioned in below.

  1. reflect.DeepEqual(a, b[:]) //by getting a slice from b array

  2. use this instead of reflect package because reflect is not good for performance as Adrian mentioned in his comment

bytes.Equal(a, b[:])

  1. create b directly as a slice with length of a if there is no need to use it as an array.
var b = make([]byte, len(a))
bytes.Equal(a, b)

Upvotes: 3

Zombo
Zombo

Reputation: 1

This does it:

package main
import "bytes"

func main() {
   var (
      a = []byte("qwedsa")
      b [6]byte
   )
   copy(b[:], a)
   println(bytes.Equal(a, b[:]))
}

https://golang.org/pkg/bytes#Equal

Upvotes: 3

Related Questions