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?
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.
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?
read/write
as opposed to just “read”)If you need these characteristics on your method call, use a pointer receiver.
b) Reasons when use value receiver?