Golang method expressions
What are method expressions?
Coming from a C++ background, I’ll allow myself to use a C++ example. If you know C++, Golang’s method expressions are very similar to member pointers. The code is relatively simple and even if you’re not a C++ enthusiast it should be possible to understand the intentions
Here’s a short C++ recap:
|
|
In C++, member pointers allow to obtain a pointer to either a member function
or a variable. The pointer itself is disassociated from any particular class
instance. Thanks to that, member pointers were often used as delegates.
Nowadays these are superseded by lambdas or std::bind
although the usage of
the latter is rather discouraged as well. Right, but this is a golang post,
isn’t it? Here’s how method expressions work in golang:
|
|
The expression
(*T).bar
yields a function of signature:
func (t *T, i int) int
The language specification goes into more details here.
Is this a syntactic sugar?
Quite right, it is. It’s similar to having an anonymous function, formed the following way:
|
|
This is of course tedious and a bit manual.
Why is this useful?
Personally, I’ve used method expressions to form a dispatching table/map. Consider the following:
|
|
Thanks to such approach the execution can be driven by data. This is especially useful when writing i.e. an emulator. In the above example, I’ve allowed myself to use Golang generics to define a delegate type… but that’s a topic for a completely different post.