Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing pointers in Go

Tags:

pointers

go

I am reading in my Go book that pointers are comparable. It says: two pointers are equal if and only if they Point to the same variable or both are nil.

So why is my following code printing 'true' when comparing two pointers which are pointing to two different variables?

func main() {
    var p = f()
    var q = f2()
    fmt.Println(*p == *q) // why true?
}

func f() *int {
    v := 1
    return &v
}

func f2() *int {
    w := 1
    return &w
}
like image 663
fufex79 Avatar asked Aug 26 '26 03:08

fufex79


1 Answers

You aren't comparing the pointers themselves because you use the 'dereference operator' * which returns the value stored at that address. In your example code, you've called the methods which returned two different pointers. The value stored at each of those different addresses happens to be 1. When you derefernce the pointer you get the value stored there so you're just comparing 1 == 1 which is true.

Comparing the pointers themselves you get false;

package main

import "fmt"

func main() {
    var p = f()
    var q = f2()
    fmt.Println(*p == *q) // why true?

    fmt.Println(p == q) // pointer comparison, compares the memory address value stored
    // rather than the the value which resides at that address value
    
    // check out what you're actually getting
    fmt.Println(p) // hex address values here
    fmt.Println(q)
    fmt.Println(*p) // 1
    fmt.Println(*q) // 1
}

func f() *int {
    v := 1
    return &v
}

func f2() *int {
    w := 1
    return &w
}

https://play.golang.org/p/j2FCGHrp18

like image 154
evanmcdonnal Avatar answered Aug 29 '26 13:08

evanmcdonnal