通过参考或价值 [英] By reference or value

查看:91
本文介绍了通过参考或价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下结构的实例

 类型Node结构{
id字符串
名称字符串
地址字符串
conn net.Conn
enc json.Encoder
dec json.Decoder
in chan * Command
out chan * Command
clients map [string] ClientNodesContainer
}

我无法理解何时应该通过引用发送结构,何时应该通过值发送它(考虑到我不想对该实例进行任何更改),是否有经验法则可以更容易地做出决定?



我能找到的所有数据都是通过值来发送一个结构体的,但是它的小或者便宜的复制,但是小的真的意味着小于64位的地址吗?



<如果有人可以指出一些更明显的规则,那么很高兴。 这个规则很简单:


在Go中没有通过引用传递/发送的概念,您只需传递值即可。
blockquote>

关于是否将结构的值或指向结构的指针(这不是通过引用调用!)的问题:


  1. 如果您想修改函数或方法中的值:传递一个指针。
  2. 如果您不想修改该值:


    1. 如果您的结构体:使用指针

    2. 否则:没关系。


    所有这些考虑复制花费你多少时间都是浪费时间。副本价格便宜,即使是中型结构。传递指针可能是在分析之后的一个合适的优化



    您的结构并不大。一个大的结构体包含像 wholeWorldBuf [1000000] uint64 这样的字段。
    像你这样的微小结构可能会也可能不会从传递指针和任何给出建议哪一个更好的人撒谎中受益:这一切都取决于你的代码和调用模式。

    如果用完了合理的选项并且分析显示时间花在复制结构上:尝试使用指针。

    if i had an instance of the following struct

    type Node struct {
        id          string 
        name        string  
        address     string
        conn        net.Conn
        enc         json.Encoder
        dec         json.Decoder
        in          chan *Command
        out         chan *Command
        clients     map[string]ClientNodesContainer
    }
    

    i am failing to understand when i should send a struct by reference and when should i send it by value(considering that i do not want to make any changes to that instance), is there a rule of thumb that makes it easier to decide?

    all i could find is send a struct by value when its small or inexpensive to copy, but does small really mean smaller than 64bit address for example?

    would be glad if someone can point some more obvious rules

    解决方案

    The rule is very simple:

    There is no concept of "pass/send by reference" in Go, all you can do is pass by value.

    Regarding the question whether to pass the value of your struct or a pointer to your struct (this is not call by reference!):

    1. If you want to modify the value inside the function or method: Pass a pointer.
    2. If you do not want to modify the value:

      1. If your struct is large: Use pointer.
      2. Otherwise: It just doesn't matter.

    All this thinking about how much a copy costs you is wasted time. Copies are cheap, even for medium sized structs. Passing a pointer might be a suitable optimization after profiling.

    Your struct is not large. A large struct contains fields like wholeWorldBuf [1000000]uint64. Tiny structs like yours might or might not benefit from passing a pointer and anybody who gives advice which one is better is lying: It all depends on your code and call patterns.

    If you run out of sensible options and profiling shows that time is spent copying your structs: Experiment with pointers.

    这篇关于通过参考或价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆