3

I wrote a code and want to check the equality of two slices like:

package main

import (
    "fmt"
)

func main() {
    s := []int{1, 2, 3}

    s2 := []int{1, 2, 3}

    fmt.Println(s == s2)

}

When I run this sample code to compare two slices it panics with error slice can only be compared to nil. I searched and found (Equality (Identity) of Go Slices) that I need to do the comparison myself but what is the underlying reason(s) that comparison is not available for the slice type like the one we have for arrays?

rezakamalifard
  • 1,289
  • 13
  • 24
  • 7
    Is a slice equal if the elements are equal, or if the backing arrays are equal, or if the headers are equal? There's no correct answer, so it's undefined. – JimB Jun 23 '20 at 01:55
  • @JimB When I compare two slices I need to know if they have exactly equal elements or not like what we have for arrays. My question what is the reason behind this error and why the comparison is not available for slice type. – rezakamalifard Jun 23 '20 at 02:04
  • 2
    @rezakamalifard The omission of slice comparison is not an error. The language designers left it out for the reasons stated by JimB. – Charlie Tumahai Jun 23 '20 at 02:10
  • If you want to compare slices by the equality of the individual values, then you are free to do so, you just can't use `==`. – JimB Jun 23 '20 at 02:12
  • I know that I can do this myself but my question is that why there's no == for slices. I think there should be a more technical reason related to the nature of slices because language designers already added == for arrays. If they wanted us to do the comparison ourselves why they added it for arrays? – rezakamalifard Jun 23 '20 at 02:33
  • 1
    You can use `reflect.DeepEqual` – Hamza Anis Jun 23 '20 at 02:35
  • 2
    @rezakamalifard if `==` was implemented, do you expect it to output `true` or `false`: https://play.golang.org/p/pzqdcoJerTu (given that they have the same elements https://play.golang.org/p/LEiySbjaFXx) – zerkms Jun 23 '20 at 02:41
  • 1
    @rezakamalifard The difference between arrays and slices is that there is one way to define `==` for arrays and three ways to define `==` for slices. – Charlie Tumahai Jun 23 '20 at 02:47
  • If those two `slices` are `byte` then can use library function `bytes.Compare` see this [Example](https://play.golang.org/p/UKth2vzO7op) – Arun Jun 23 '20 at 04:27

0 Answers0