Methods in Golang

In Go, a method is a function that is associated with a specific type, known as its receiver type. Methods are a way to define behaviors for custom types, and they enable you to attach functions to your own defined data types.

Here are some key points about methods in Go:

  • A method is declared with a receiver type before the method name. The receiver type can be any named type or a pointer to a named type.
  • Methods can only be defined for types declared in the same package as the method. However, you can define methods for built-in types via type aliasing.
  • Methods can have value receivers (non-pointer) or pointer receivers. Choosing between them depends on whether you want to modify the original value or not.
  • Value receivers receive a copy of the value, while pointer receivers receive a reference to the value, allowing modification of the original value.
  • Methods with pointer receivers are more common when you want to modify the value, as they avoid copying the entire value.
Read More