Best practice: Should you use methods or functions?

When building a Go program, one of the key decisions isHow to organize program functions.

Especially in this article, I will explainWhen should I use methods and when should I use functions.

The definitions of these two options are very similar. The only difference is that the method is attached to the type:

// function
func something(s string) {}

//methods func (MyType) something(s string) {} func (*MyType) something(s string) {}

If you come from an object-oriented language such as Ruby, Python, or modern PHP, then you might want to build all your code around types and methods, because this is exactly how these languages force you to think. There are no external objects and methods.

If you are fromJavaScriptIn the background, you might think of methods as object prototype methods, if you are using good old pre-classed JavaScript, and functions are just functions, then I think this is a good comparison.

This is a matter of the country

The function does not depend on the state in any way.

Define a function based on mathematics, provide some input parameters, and the output value will always be the same.

On the other hand, methods are closely linked to the types they are connected to when they define their behavior and use their values.

They get some value from the types defined for them, and if they have pointer receivers, they can manipulate their state.

If your methods do not depend on state, you should define them as functions.


Inspired by Steve Francia's speech "7 Common Mistakes in Go and How to Avoid Mistakes":