Introduction to Methods
Explore the concept of methods in Go, focusing on how methods act on receiver types including structs and aliases. Understand method syntax, receiver rules, method sets, and practical usage through examples. This lesson clarifies how Go implements object-oriented behavior without traditional classes and method overloading, helping you write more structured and idiomatic Go code.
We'll cover the following...
What is a method?
Structs look like a simple form of classes, so an OO programmer might ask, where are the methods of the class? Again, Go has a concept with the same name and roughly the same meaning. A Go method is a function that acts on a variable of a certain type, called the receiver. Therefore, a method is a special kind of function.
Note: A method acting on a variable in Go is similar to the object of a class calling its function in other OO languages, using a
.selector, e.g.,object.function().
The receiver type can be (almost) anything, not only a struct type. Any type can have methods, even a function type or alias types for int, bool, string, or array. However, the receiver cannot be an interface type since an interface is an abstract definition and a method is the implementation. Trying to do so generates the compiler error: invalid receiver type.
Lastly, a method cannot be a pointer type, but it can be a pointer to any of the allowed types. The combination of a (struct) type and its methods is the Go equivalent of a class in OO. One important difference is that the code for the type and the methods binding to it are not grouped together. ...