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
}
You aren't comparing the pointers themselves because you use the 'derefernce 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
}
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
}