At a certain moment, when working with Golang we mentally start thinking about classes and methods, just the regular OOP way of working.
In the OOP approach, a Struct
data type can be seen as a Class definition, the Blueprint
for incoming objects, where, variables or even arrays can be seen as attributes and some functions can be seen as methods.
But that's not all correct.
The ideal scenario here is that we need a way to extending a base type to add some extra functionality. By base types, I'm referring to strings, integers, arrays, maps, and so on. Any custom method that can be appliable to an instance, we can 'associate' it to an OOP object.
This can be achieved by the use of Receivers
, this is like an object function that expects a certain type of element to invoke it.
You can understand this better with an example.
func (c car) startEngine() {
....
}
Here:
- The
c
is the actual copy of the car "instance" we are working with - The
car
references the working variable - The
startEngine()
is the function itself.