douchao1957 2017-01-25 21:52
浏览 42
已采纳

为什么这些golang指针不相等?

In the example below I check the equality of two pointers

  • The pointers are pointing to the same address
  • They are not the same pointer

How do I check if two pointers are pointing to the same address? I do not want to check if the contents of both pointers are equal.

package main

import (
    "fmt"
)

type Map struct {}
type Fragment struct {
    Map *Map
}

func (m1 Map) NewFragment() (f Fragment) {
    f.Map = &m1
    return
}


var m Map = Map {}

func main() {
    f := m.NewFragment()
    fmt.Println(f.Map == &m) // false
    fmt.Println(*f.Map == m) // true

}

Go Playground

  • 写回答

2条回答 默认 最新

  • duanjiwei1283 2017-01-26 02:19
    关注

    As JimB answered, you can use == to compare pointers. The reason this program behaves that way is because when you call the NewFragment method, a copy is made of the receiver. In this case, that means the line f.Map = &m1 is taking the address of the copy, not the original object. Therefore, the pointers are different (f.Map != &m), and the values are the same (*f.Map == m).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?