deeper understanding of go’s function receivers
tags: learning go programming
content
we have a struct:
type Book struct {
title string
isRead bool
}and we have two functions:
// func 1
func readBook1(b *Book) {
(*b).isRead = true
}
// func 2
func (b *Book) readBook2() {
(*b).isRead = true
}and we have two different ways to call the readBook functions:
func main() {
book := Book{"title", false}
readBook1(&book)
book.readBook2()
}- the difference between these two functions is:
- the first one is a regular function (without receiver)
- the second one is a struct method
- struct methods associate a function to a struct, kinda feels like OOP: it associates an object’s natural behavior with the object itself, instead of making that behavior a separate function that’s unrelated to the object.
in fact, methods are just functions with receiver arguments → A Tour of Go
- methods allow methods chaining, e.g.:
book.readBook().readBook() - methods are required for interface implementation