Golang: What is a receiver function?

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


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


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.

Posted in GoTagged

2 thoughts on “Golang: What is a receiver function?

  1. In your last example, would the receiver type “database” be capitalized, like this: “(d Database)” — since it needs to match the name of the struct type?

    1. It definitely does need to match. Sorry about that typo! I really should have caught it when I ported the code over from my IDE to the browser.

Leave a Reply

Your email address will not be published. Required fields are marked *