dtc66318 2014-02-27 01:31
浏览 17
已采纳

您如何确定函数是否应该像接收器一样使用指针?

Consider a binary tree node:

type Node struct {
    value uint8
    left, right *Node
}

If I want to add a function to each Node, should it be:

A:  func (n *Node) height() int

or

B:  func (n Node) height() int

I want to know which of A or B you would choose and why.

I can model linked lists or recursive structs, but I don't know when the receiver should be a pointer or not-a-pointer.

  • 写回答

2条回答 默认 最新

  • duanqu9292 2014-02-27 02:11
    关注

    The main difference is the idea of pass by value vs pass by reference

    When you're using example A you're passing be reference, meaning that any changes you apply to n inside of func (n *Node) height will apply to the Node you're using to call Node.height().

    By comparison, what you're doing in example B is passing by value where you're really just passing a copy of the Node you're using to call Node.height() so any changes to that Node will not apply outside of the function.

    Here is a small playground to demonstrate the differences: http://play.golang.org/p/JodPRPBHDg

    Notice in the example that when you call node.incHeight(), it goes to the function:

    func (n Node) incHeight() uint8 {
      n.value++
      return n.value
    }
    

    Because this is pass by value the node.value is still the same unless you store the returned value as node.value. However, if you call node.incrementHeight() it goes to the function:

    func (n *Node) incrementHeight() {
      n.value++
      return
    }
    

    This will change the value of node.value without needing to return anything because its referencing the original struct, rather than a copy of the struct.

    So in answer to which would you choose and why, it really depends on whether you want to be able to make lasting changes to the struct you're using to call the function or if you'd rather just pass a copy that can see and alter the values but only while within the function and not have any lasting effects on the original struct.

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

报告相同问题?

悬赏问题

  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 被蓝屏搞吐了,有偿求帮解答,Ai回复直接拉黑
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并