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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里