doujia8801 2016-08-23 23:46
浏览 29
已采纳

变量赋值和通过引用传递之间有什么区别?

I'm pretty new to golang, and compiled languages in general, so please excuse my ignorance. In some code like this:

package main

import "fmt"

func assign() int {
  return 1
}

func reference(foo *int) int {
  *foo = 2
  return 0
}

func main() {
  var a, b int

  a = assign()
  reference(&b)

  fmt.Println(a)
  fmt.Println(b)
}

...what is the practical difference between assigning the value to a vs. passing b by reference?

In terms of real-world code, why does json.Unmarshal() require you to pass a pointer to your empty variable rather than just returning the Unmarshalled value so you can assign it to your variable?

  • 写回答

1条回答 默认 最新

  • duandaiqin6080 2016-08-24 02:11
    关注

    Passing by value requires copying of parameters, however in case of reference, you just send the pointer to the object. Golang does pass by value by default, including for slices.

    For the specific question about json.Unmarshal, I believe the reason is so that the Unmarshal code can verify whether the object passed in contains the same field names with compatible types as found in the json. For example, if json has a repeated field, there needs to be a corresponding slice in the object we are unmarshaling into.

    So, we need to pass in the struct that we want the json string to unmarshal into. It needs to be a pointer so that Unmarshal can populate the fields. If you just pass a generic interface, Unmarshal will return a map. If Unmarshal did not take a pointer to a struct/interface, it could have been implemented to always return a map, but I think it is more useful this way.

    This is a simple example, but might be useful - https://play.golang.org/p/-n8euepSS0

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

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码