gpt4 book ai didi

go - 为什么在值而不是指针上定义方法?

转载 作者:IT王子 更新时间:2023-10-29 01:27:17 25 4
gpt4 key购买 nike

查看示例 Go 代码,有些地方不一致。许多代码在指针类型上定义它们的方法,例如:

func (p *parser) parse () {...}

但是其他一些代码只在类型上定义方法,而不是指向它的指针:

func (s scanner) scan () {...}

做后者有充分的理由吗?按值而不是指针传递对象真的更有效吗?

一个原因是“我不能改变这个对象”,但这无论如何都是大对象的问题(你会按值传递大结构只是为了标记它不能被方法改变吗?)

最佳答案

幸运的是,这在 Go FAQ 中:

Should I define methods on values or pointers?

func (s *MyStruct) pointerMethod() { } // method on pointer
func (s MyStruct) valueMethod() { } // method on value`

For programmers unaccustomed to pointers, the distinction between these two examples can be confusing, but the situation is actually very simple. When defining a method on a type, the receiver (s in the above examples) behaves exactly as if it were an argument to the method. Whether to define the receiver as a value or as a pointer is the same question, then, as whether a function argument should be a value or a pointer. There are several considerations.

First, and most important, does the method need to modify the receiver? If it does, the receiver must be a pointer. (Slices and maps act as references, so their story is a little more subtle, but for instance to change the length of a slice in a method the receiver must still be a pointer.) In the examples above, if pointerMethod modifies the fields of s, the caller will see those changes, but valueMethod is called with a copy of the caller's argument (that's the definition of passing a value), so changes it makes will be invisible to the caller.

By the way, pointer receivers are identical to the situation in Java, although in Java the pointers are hidden under the covers; it's Go's value receivers that are unusual.

Second is the consideration of efficiency. If the receiver is large, a big struct for instance, it will be much cheaper to use a pointer receiver.

Next is consistency. If some of the methods of the type must have pointer receivers, the rest should too, so the method set is consistent regardless of how the type is used. See the section on method sets for details.

For types such as basic types, slices, and small structs, a value receiver is very cheap so unless the semantics of the method requires a pointer, a value receiver is efficient and clear.

所以是的,它主要用于语义。在处理并发时,知道一个方法是无副作用的是一件好事,因为这自动意味着不需要锁定。除了全局变量和引用类型之外,值接收器强烈暗示您的方法没有副作用。

关于go - 为什么在值而不是指针上定义方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22406530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com