I was going through some go tutorials but I'm not able to understand what method expressions are in go. Can anyone explain this code to me and why/when I should use it?
// Method call with "method expression" syntax
func main() {
dog := Dog{}
b := (*Dog).Bark // method expression
b(&dog, 5)
}
type Dog struct {}
// Methods have a receiver, and can also have a pointer
func (d *Dog) Bark(n int) {
for i := 0; i < n; i++ {
fmt.Println("Bark");
}
}
A method expression is a function that can be called like a regular function, except that you also pass the object to act on as the first argument. This is because it needs to know which object to use.
Normally, you would just use the following:
d := &Dog{}
d.Bark(5)
But using a method expression, you can "save" the function, allowing you to pass it to something else. For example, you could choose to use (*Dog).Bark
or (*Dog).Sit
as an action, and call it from a helper. eg:
func main() {
var b func(*Dog, int)
if (shouldBark) {
b = (*Dog).Bark
} else {
b = (*Dog).Sit
}
d := Dog{}
DoAction(b, &d, 3)
}
func DoAction(f func(*Dog, int), d *Dog, n int) {
f(d, n)
}
The specific syntax (*Dog).Bark
means that you are deriving a function for a method with pointer receiver.
Honestly, these are not very frequently used. I would recommend you get a good grasp of the language first (eg: take the entire Go tour), then explore less used functionality at a later date.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments