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
}

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.

Posted in GoTagged

Leave a Reply

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