Comparing pointers in Go
Solution 1
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
Solution 2
package main
import "fmt"
func main() {
var p = f()
var q = f2()
fmt.Println(*p == *q)
/* is true, since *p = *q = 1 */
fmt.Println(p == q)
/* is false, since *p and *q store two different memory addresses */
}
func f() *int {
v := 1
return &v
}
func f2() *int {
w := 1
return &w
}
https://play.golang.org/p/i1tK4hhjOf
fufex79
Updated on December 07, 2021Comments
-
fufex79 over 2 years
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 }
-
UnholySheep over 8 yearsAre you sure about that? the two variables should hold the values returned by the functions (which are the addresses of the results)
-
fufex79 over 8 yearsOk, understood. But why then f() == f() is false. Each call of f() should return a pointer pointing to the same variable?
-
JimB over 8 yearsWhat methods do you think are being compared? He's comparing two
*int
, both of which are 1, so they're equal after dereferencing. -
UnholySheep over 8 years@fufex79 the values would only be equal if the compiler optimised the function call to return the same value (the same address), however he shouldn't do that, as that value may be later modified. so each call to the function creates a new variable (with a new address)
-
evanmcdonnal over 8 years@JimB as I stated originally, I wasn't sure of what comparison was being done, only that it wasn't the pointers. I thought those were function pointers, not just pointers holding the returned
int*
haha. Anyway, I've edited to remove the random nonsense about equality comparisons on functions. The main points are still true... The values are equal because he dereferenced.