2 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊
您沒有比較指針本身,因?yàn)槟褂昧恕叭∠眠\(yùn)算符” *,它返回存儲(chǔ)在該地址的值。在您的示例代碼中,您調(diào)用了返回兩個(gè)不同指針的方法。存儲(chǔ)在每個(gè)不同地址的值恰好是1. 當(dāng)您取消引用指針時(shí),您會(huì)得到存儲(chǔ)在那里的值,因此您只是在比較1 == 1哪個(gè)是真的。
比較指針本身,你會(huì)得到錯(cuò)誤;
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貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
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 關(guān)注
- 185 瀏覽
添加回答
舉報(bào)