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 关于#python#的问题:求帮写python代码
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?