3 ms·
On one hand, it is rational if you think of Go functions "on a type" as just having an extra argument, but then one might ask, why bother with the special synta
by kroltan 6y ago
On one hand, it is rational if you think of Go functions "on a type" as just having an extra argument, but then one might ask, why bother with the special syntax at all?
Just go the C way and if you want to take a "self", actually take it as a regular parameter. That is: (sorry if the syntax is wrong, I have never used Go)
func (f *Foo) sayHello() { ... }
Would become
func sayHello(f *Foo) { ... }
Heck, if you want to keep the value.sayHello() syntax, you can, which would still allow you to build fluent interfaces or whatnot, with the bonus point of being UFCS!
- AlexCoventry 6y ago> why bother with the special syntax at all? It dovetails nicely with interfaces.
- throwaway34241 6y agoThey basically are functions with an additional argument. You can call them with the method syntax, but you can also call them like a regular function. To use your first example, you can also call it like this: (*Foo).sayHello(f) // the same as f.sayHello() It's mainly useful when you want to get a reference to the method itself: f := (*Foo).sayHello // a function that takes one arg of type *Foo For most purposes the two are the same, the main difference is with with how interfaces work in Go. Functions declared with the special syntax can be used to satisfy interfaces, which in Go means keeping some run-time type information around.
- andreygrehov 6y agoSome people do exactly that and avoid methods altogether. It's perfectly valid to use: func sayHello(f *Foo) { ... } One major difference between functions and methods in Go is you can have multiple methods with same name while no two functions with the same name can be defined in a package. Also, there is a subtle difference, which is more subjective, between user.IsActive() and IsActive(user). The former explicitly implies that you operate on a user, whereas the later one isn't that obvious, like what if I do IsActive(group), is that also allowed? I like that Go is not trying to be super flexible, but it also nicely holds a niche of a slightly improved (in terms of usability) C.