golang 接收者 指针_最佳实践:指针还是价值接收者?

golang 接收者 指针

Common dilemma when defining the methods of a struct.

定义结构方法时的常见难题。

In particular when deciding your method receivers, should you use pointer receivers or value receivers?

特别是在确定方法的接收者时,应该使用指针接收者还是值接收者?

func (t *Type) Method() {} //pointer receiver

vs

func (t Type) Method() {} //value receiver

Method receivers can be assimilated to function arguments in their behavior, and everything applicable to passing a pointer or a value as a function argument still applies for method receivers.

方法接收器可以在其行为上与函数自变量相似,并且适用于将指针或值作为函数自变量传递的所有内容仍然适用于方法接收器。

什么时候应该使用指针接收器 (When should you use pointer receivers)

修改接收者 (Modify the receiver)

If you want to change the state of the receiver in a method, manipulating the value of it, use a pointer receiver. It’s not possible with a value receiver, which copies by value. Any modification to a value receiver is local to that copy.

如果要在方法中更改接收器的状态并对其值进行操作,请使用指针接收器 。 对于按值复制的值接收器,这是不可能的。 对值接收器的任何修改都是该副本的本地内容。

优化 (Optimization)

If the struct you’re defining the method on is very large, copying it would be far too expensive than using a value receiver.

如果要在其上定义方法的结构很大,则复制它比使用值接收器要昂贵得多。

Value receivers operate on a copy of the original type value. This means that there is a cost involved, especially if the struct is very large, and pointer received are more efficient.

值接收器对原始类型值的副本进行操作。 这意味着要付出一定的代价,尤其是在结构非常大且指针接收效率更高的情况下。

当价值接收者更好时 (When value receivers are better)

If you don’t need to edit the receiver value, use a value receiver.

如果您不需要编辑接收器值,请使用值接收器

Value receivers are concurrency safe, while pointer receivers are not concurrency safe.

值接收器是并发安全的,而指针接收器不是并发安全的

什么时候应该权衡 (When you should make a tradeoff)

There is a situation when you might want to use pointer receivers for methods where you’d normally use a value receiver, and it’s when you have other pointer receivers defined on that type, and for consistency you should use pointer receivers across all the methods.

在某些情况下,您可能希望对通常使用值接收器的方法使用指针接收器,并且当您在该类型上定义了其他指针接收器时,为了保持一致性 ,应在所有方法之间使用指针接收器。

阅读更多 (Read more)

翻译自: https://flaviocopes.com/golang-methods-receivers/

golang 接收者 指针

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值