英文:
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) 何时使用指针接收器?
- 当你想要实际修改接收器(读/写,而不仅仅是“读取”)时。
- 结构体非常大,深拷贝代价很高。
- 一致性:如果结构体上的某些方法具有指针接收器,其他方法也应该有。这样可以保证行为的可预测性。
- 如果接收器是一个大的结构体或数组,使用指针接收器更高效。
如果你需要这些特性,请使用指针接收器。
b) 何时使用值接收器?
- 如果接收器是一个map、func或chan,请不要使用指针。
- 如果接收器是一个切片,并且方法不会重新切片或重新分配切片,请不要使用指针。
英文:
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?
- You want to actually modify the receiver (
read/write
as opposed to just “read”) - The struct is very large and a deep copy is expensive.
- Consistency: if some of the methods on the struct have pointer receivers, the rest should too. This allows predictability of behavior.
- 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?
- If the receiver is a map, func or chan, don't use a pointer to it.
- If the receiver is a slice and the method doesn't reslice or reallocate the slice, don't use a pointer to it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论