Comparing Pointers in Golang

In Go, you can compare pointers using the equality (==) and inequality (!=) operators. Comparing pointers allows you to check whether two pointers point to the same memory address or not.

Here’s how you can compare pointers:

package main

import "fmt"

func main() {
    x := 42
    y := 42
    p1 := &x
    p2 := &x
    p3 := &y

    fmt.Println("p1 == p2:", p1 == p2) // true, p1 and p2 point to the same address
    fmt.Println("p1 == p3:", p1 == p3) // false, p1 and p3 point to different addresses
}

Output :

p1 == p2: true
p1 == p3: false

In this example, p1 and p2 point to the same memory address because they both point to the variable x. On the other hand, p3 points to a different memory address because it points to the variable y.

Remember that pointer comparison is based on memory addresses, not the values stored at those addresses.

Here’s another example that demonstrates pointer comparison with a slice:

package main

import "fmt"

func main() {
    slice1 := []int{1, 2, 3}
    slice2 := []int{1, 2, 3}
    slice3 := slice1

    p1 := &slice1
    p2 := &slice2
    p3 := &slice3

    fmt.Println("p1 == p2:", p1 == p2) // false, p1 and p2 point to different slices
    fmt.Println("p1 == p3:", p1 == p3) // true, p1 and p3 point to the same slice
}

Output :

p1 == p2: false
p1 == p3: true

In this example, p1 and p2 point to different slices, even though the content of the slices is the same. Therefore, p1 == p2 returns false. On the other hand, p1 and p3 point to the same slice, so p1 == p3 returns true.

Pointer comparison is always based on memory addresses. If two pointers point to the same memory address, the comparison will yield true, regardless of the contents of the data they point to. If they point to different memory addresses, the comparison will yield false.