我在我的 Go 书中读到指针是可比较的。它说:两个指针相等当且仅当它们指向同一个变量或两者都为零。
那么为什么我的以下代码在比较指向两个不同变量的两个指针时打印“真”?
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
}
最佳答案
您没有比较指针本身,因为您使用了“取消引用运算符”*
,它返回存储在该地址的值。在您的示例代码中,您调用了返回两个不同指针的方法。存储在每个不同地址的值恰好是 1
。当你取消引用指针时,你会得到存储在那里的值,所以你只是比较 1 == 1
这是真的。
比较指针本身你会得到错误;
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
}
关于pointers - 在 Go 中比较指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34276205/