Go函数参数

huangapple go评论84阅读模式
英文:

Go function parameters

问题

func (db *Database) VerifyEmail(emailAddress string) (*data.UserName, error) {
....
}

请问有人可以帮忙解释一下上面的函数的1.作用和2.原因吗?从文档这本书中我可以看出,VerifyEmail函数以emailAddress作为参数,并返回我认为是用户名的内存地址。

然而,(db *Database)是什么意思?我的意思是为什么将其放在func之后和函数名之前?以及将内存地址作为指针传递给函数的原因可能是什么,而不是传递表示它的变量?

英文:
func (db *Database) VerifyEmail(emailAddress string) (*data.UserName, error) {
....
}

Can someone please help clarify 1.what and 2.why with the above function? From the docs and this book I can tell that VerifyEmail is taking in emailAdress as a parameter and returning what I think is the memory address to a username.

However, what does (db *Database) do? I mean why put that after func and before the name of the function? And what may be some reasons to pass the memory address to a function as a pointer as opposed to the variable representing it?

答案1

得分: 2

(*db Database)在方法名前面是方法接收器,类似于其他语言中的"this"关键字,如果对象可能很大或者方法需要修改对象,你可以使用指针--如果你复制它,方法只能修改对象的副本。

英文:

The (*db Database) in front of the method name is the method receiver, similar to other languages' "this", and you use a pointer if the object may be large or the method may need to change the object--if you copy it, the method can only change its copy of the object.

答案2

得分: 1

在Go语言中,你可以使用指针和非指针方法接收器来定义方法。格式类似于func (t *Type)func (t Type)

那么指针和非指针方法接收器之间有什么区别呢?

a) 何时使用指针接收器?

  1. 当你想要实际修改接收器(读/写,而不仅仅是“读取”)时。
  2. 结构体非常大,深拷贝代价很高。
  3. 一致性:如果结构体上的某些方法具有指针接收器,其他方法也应该有。这样可以保证行为的可预测性。
  4. 如果接收器是一个大的结构体或数组,使用指针接收器更高效。

如果你需要这些特性,请使用指针接收器。

b) 何时使用值接收器?

  1. 如果接收器是一个map、func或chan,请不要使用指针。
  2. 如果接收器是一个切片,并且方法不会重新切片或重新分配切片,请不要使用指针。
英文:

In Go, you can define methods using both pointer and no-pointer method receivers. The formate feels like func (t *Type) and func (t Type) respective.

So what’s the difference between pointer and non-pointer method receivers?

a) Reasons when use pointer receiver?

  1. You want to actually modify the receiver (read/write as opposed to just “read”)
  2. The struct is very large and a deep copy is expensive.
  3. Consistency: if some of the methods on the struct have pointer receivers, the rest should too. This allows predictability of behavior.
  4. If the receiver is a large struct or array, a pointer receiver is more efficient.

If you need these characteristics on your method call, use a pointer receiver.

b) Reasons when use value receiver?

  1. If the receiver is a map, func or chan, don't use a pointer to it.
  2. If the receiver is a slice and the method doesn't reslice or reallocate the slice, don't use a pointer to it.

huangapple
  • 本文由 发表于 2015年3月22日 09:09:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/29189878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定