Golang: What is a receiver function?
Posted on June 30, 2019  (Last modified on April 12, 2023 )
2 minutes • 224 words
This project uses these versions of languages, frameworks, and libraries.
-
go
: 1.16
This tutorial may work with newer versions and possibly older versions, but has only been tested on the versions mentioned above.
Classes aren’t really a thing in Go, so you cant have instance methods (like Java or similar ), however, you may have noticed some functions in Go that appear to be instance methods. These are Go’s receiver functions .
The way they work is quite simple. If you have a struct like so:
type Database struct {
Host string
Port int
User string
Password string
Dbname string
Driver string
}
You could write a function that takes the struct in as a parameter. For example:
d := Database{...}
func getDatabaseRoot(db *Database) {
return db.Host + ":" + db.port
}
getDatabaseRoot(d)
Go’s receiver function
However, Go gives us the ability to specify that getDatabaseRoot is a function that belongs to that Struct, via receiver functions. Instead of the above, we can write:
d := Database{...}
func (d Database) getDatabaseRoot() {
return d.Host + ":" + db.port
}
d.getDatabaseRoot();
And Voilà. That’s how you define and user a receiver function in Go!
It’s worth mentioning that there are some concerns with Go’s receiver functions in regards to testability. Namely, receiver functions are, as far as I know, something you can’t stub which can make testing functions that depend on those functions a real pain.
If you’re interested in learning more about Go, you can check out more of my articles on Google’s awesome language here .