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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
class Foo {
public:
std::string foo() {
return "foo";
}
int bar(int i) {
return i;
}
};
using FooPtr = std::string (Foo::*)();
using BarPtr = int(Foo::*)(int);
int main(int argc, const char *argv[])
{
Foo f{};
FooPtr fooPtr = &Foo::foo;
BarPtr barPtr = &Foo::bar;
std::cout << (f.*fooPtr)() << std::endl;
std::cout << (f.*barPtr)(123) << std::endl;
return 0;
}
|
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: