Go for C# developers: functions vs methods

I must admit that I often use the words function and method interchangeable. Probably because I was once taught that a method is a function that does not return anything. In the Go vocabulary however there is a clear difference and a nice method gotcha!

Another common mistake C# developers do is to talk about class methods in Go. Go people hate this and politely let you know there are no classes in Go. So to all C# developers out there; what "looks" like a class method, that is a function that is defined as being attached to a specific type is in Go called a method. Everything else is a function.

A really fun gotcha with methods in Go is that if you declare your receiver as being by-value then you can create setters that don't change the instance used to call the method. Here is a snippet to demonstrate that. Cut-n-pasting method receiver definitions can definitely lead to bugs if you do not consider your definitions carefully.

No comments:

Post a Comment