Cookies management by TermsFeed Cookie Consent

🍕 Compare two slices in Go

introduction slice strings

Slices in Go are not comparable, so a simple equality comparison a == b is not possible. To check if two slices are equal, write a custom function that compares their lengths and corresponding elements in a loop.

Note that comparing two arrays is possible:

a := [2]string{"strawberry", "raspberry"}
b := [2]string{"strawberry", "raspberry"}
fmt.Printf("slices equal: %t\n", a == b)

package main

import "fmt"

func stringSlicesEqual(a, b []string) bool {
    if len(a) != len(b) {
        return false
    }
    for i, v := range a {
        if v != b[i] {
            return false
        }
    }
    return true
}

func main() {
    a := []string{"strawberry", "raspberry"}
    b := []string{"strawberry", "raspberry"}
    fmt.Printf("slices equal: %t\n", stringSlicesEqual(a, b))

    b = append(b, "test")
    fmt.Printf("slices equal: %t\n", stringSlicesEqual(a, b))
}

Output:

slices equal: true
slices equal: false

You can also use the reflect.DeepEqual() function that compares two values recursively, which means it traverses and checks the equality of the corresponding data values at each level. However, this solution is much slower and less safe than comparing values in a loop. A general rule of thumb when using the reflect package is: it should be used with care and avoided unless strictly necessary.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    a := []string{"strawberry", "raspberry"}
    b := []string{"strawberry", "raspberry"}
    fmt.Printf("slices equal: %t\n", reflect.DeepEqual(a, b))

    b = append(b, "test")
    fmt.Printf("slices equal: %t\n", reflect.DeepEqual(a, b))
}

Output:

slices equal: true
slices equal: false

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🧑‍🤝‍🧑 Copy a slice in Go

Learn how to make a deep copy of a slice
introduction slice

🧮 Sort a string slice containing numbers in Go

Learn how to sort strings with numbers in natural order
sort slice strings