2 回答
TA贡献1780条经验 获得超3个赞
您没有比较指针本身,因为您使用了“取消引用运算符” *,它返回存储在该地址的值。在您的示例代码中,您调用了返回两个不同指针的方法。存储在每个不同地址的值恰好是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
}
https://play.golang.org/p/j2FCGHrp18
TA贡献1911条经验 获得超7个赞
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
- 2 回答
- 0 关注
- 162 浏览
添加回答
举报