Methods — Golang
Go does not have classes. But we can define methods on types.
A method consists of the func keyword, the receiver argument, and the function body.
Method Syntax:
func (receiver receiverType) methodName(arg argType) returnType {}Methods on Struct types
Example:
This example has the struct type Person and it has the method print to print the Person type. Also it has the function printPerson that takes Person type as a argument and prints the Person type.
//this is how we access the method
receiverType.methodName()Pointer receiverType
we can also use pointer receiver type to modify the values
Example:
Get Logesh’s stories in your inbox
Join Medium for free to get updates from this writer.
Here in this example I have used the pointer receiver type to modify the value.
To call the method with pointer receiver type we don’t have to use the address operator. Go will do that automatically for us.
But this won’t work for all. For example when you implement the Stringer type (String() method) for our struct type with the Pointer receiver then we should pass the address to it while calling that method, if it is a value receiver then just passing the value to it will work. Becoz, the fmt package uses type assertion to check whether that particular type implements the Stringer type or not. For more about Stringer type checkout my article here.
Methods on Non-Struct types
We can also create methods for non-struct types.
Example:
Here we have created the method for the money type which has the float64 as its underlying type.
In this article, we have seen the methods with the value receiver and the pointer receiver type for both the Struct types and the Non-Struct types.
Hope you liked this article!
Happie Learning :)
Keep Learning!!!







