GOLANG
Anatomy of methods in Go
Go does not support the Object-Oriented paradigm but structure
resembles the class
architecture. To add methods to a structure, we need to use functions with a receiver
.
Even Go does not provide classes, we can use structures to create objects as we have learned in the previous tutorial. But in OOP, classes have properties (fields) as well as behaviors (methods) and so far we have only learned about properties of a struct that are structure fields.
💡 Behavior is a action that an object can perform. For example,
Dog
is a type ofAnimal
andDog
canbark
. Hence barking is a behavior of the classDog
. Hence any objects (instances) of the classDog
will have this behavior.
We have seen in the structures lesson, especially in the function field section that a struct field can also be a function. We can add a bark
field of type function which takes no arguments and returns a string woof woof!
. This could be one way to add methods to the struct.
But this does not adhere to the OOP concept as struct
fields do not have any idea of struct
they belong to. Hence methods come to the rescue.