🍕 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

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

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

🧠 Print the memory address of a variable in Go

Learn how to find and print the address of a variable or pointer
introduction pointer slice

🏟️ Capacity and length of a slice in Go

Learn what is the difference between length and capacity of a slice
introduction slice array