dtdb99743 2013-11-04 03:26
浏览 36
已采纳

在Go中传递指针与值

I've read this interesting blog post that is totally unrelated to Go and one thing the author said caught my attention, this following quote:

... For example, it is efficient to pass a channel as the parameter of a function all, because a channel in Go is as simple as a pointer to the channel data structure implemented in C. It is the same for map and some other types. But it is inefficient to pass an array or struct; instead, we should pass pointers to these types.

Why is it inefficient to pass pointers when using some of Go internal types or structs?

  • 写回答

2条回答 默认 最新

  • dongyi4170 2013-11-04 03:58
    关注

    The context is relevant here:

    However, the type system of Go is so complex; programmers need to know all the details about the implementation of standard types, before they can use them correctly. For example, it is efficient ...

    The author is saying that maps and channels look like values but act like pointers when they are copied.

    For other datatypes, the parameter has a * in it, which is a clear signal it could be modified in place. Often the argument has a & in front as well, which is another signal that the argument is being modified.

    When passing maps and channels, those syntactic signals are not there. That leads to unexpected results like this one:

    http://play.golang.org/p/lS1FXZnxb8

    A similar criticism could be applied to the big difference between arrays like [256]byte and slices like []byte, where the absence of a size is the only signal of different copying behavior.

    All of this being aside, the author incorrectly equates copying and inefficiency. It is true that copying sometimes requires more CPU cycles or memory accesses than passing a pointer. However, that is not always the case. It depends on the size of the structure and optimizations performed by the compiler.

    The decision to copy, i.e. pass a value, vs. pass a pointer is also about whether the argument might be modified by the function.

    For small structures and arrays which are not intended to be modified by the function, pass them by value. This eliminates an entire class of bugs caused by accidental modifications in place, and is even better than const as used in other languages, because there is no way to cheat and get around it. Of course, always be careful with embedded pointers, including maps and slices, because those may still be modified inside the function.

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。