doutang7414 2018-09-19 20:56 采纳率: 0%
浏览 47
已采纳

Go函数具有返回/签名混合类型

I'm trying to figure out how pointers work in Go and I think I'm starting to get it, but this is confusing me and I don't really know what to search for. Let's say I have the following function:

func createNode(nodeInfo string) *TreeNode {
    return &TreeNode{info: nodeInfo}
}

I understand that the function is returning the memory address of the created struct instance, but how does the function signature say *TreeNode? According to my understanding, the * is used to dereference pointers to get the value itself, so what is happening here?

Also, here:

 func zero(xPtr *int) {
  *xPtr = 0
}

func main() {
  x := 5
  zero(&x)
}

The opposite is happening where the function is accepting an argument with the * operator but the function itself is being called with & operator.

  • 写回答

1条回答 默认 最新

  • doudou3935 2018-09-19 21:18
    关注

    The * has 2 uses, one for variables and one for types:

    • For types, it signifies, that the type is a pointer, not a value directly.
    • For variables, it dereferences a pointer, as you already know. (One might also distinguish this use into to two "sub-uses", as * on the left side of assignments, as in *ptr = val sets the value the pointer is pointing to, while * usually "retrieves" the value the pointer is pointing to.)

    & on the other hand, can only be used for variables and gets the address of an object in memory.

    In your examples, the return type *TreeNode and the argument type *int signify that you are returning/expecting a pointer, according to the use for types. In contrast, *xPtr = 0 dereferences the variable xPtr.

    To know which use is the correct one in your situation, you must make clear to yourself whether you are dealing with a type or a variable.

    For a technical description, you can read the sections of the language specifications on Pointer types and Address operators.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接