Intro
We have already seen golang functions. Now the question is:
what is the difference between a function and a method in Go?
Answer is -
A method is a function that has a defined receiver, in OOP terms, a method is a function on an instance of an object.
Go doesnt have classes but structs, and we can add receiver methods on structs to add behaviour.
To add some behaviour to a struct you can have it be a method reciever. You can use a value reciever or a pointer reciever.
package main
import "fmt"
type MyType struct{
Name string
}
//value reciever
func (mt MyType) SayName(){
fmt.Println(mt.Name)
}
//pointer reciever
func (mt *MyType) SayAgain(){
fmt.Println(mt.Name)
}
//example of custom builtin type
type MySlice []string
func (ms MySlice) Length()int{
return len(ms)
}
func main (){
mt := MyType{Name:"Janeway"}
mt.SayName()
ms := MySlice{"test"}
fmt.Println(ms.Length())
}
So what’s happening here? Well we are creating and assigning a value of type MyType to the variable mt. Then we are calling the method SayName on that Value. This is actually a bit of sugar from Go. Under the covers this is essentially what is happening:
package main
import "fmt"
type MyType struct {
Name string
}
func SayName(mt MyType) {
fmt.Println(mt.Name)
}
func SayAgain(mt *MyType) {
fmt.Println(mt.Name)
}
func main() {
mt := MyType{Name: "Janeway"}
SayName(mt)
SayAgain(&mt)
}
Output:
Janeway
1
So essentially the compiler is using the the definition before the method name as the first argument to the function. As with Javascript you can assign functions to most types. For e.g:
package main
import "fmt"
type MyMap map[string]string
func(m MyMap)Get(val string)string{
return m[val]
}
func(m MyMap)Put(key,val string){
m[key] = val
}
func main(){
mMap := MyMap{}
mMap.Put("voyager","Janeway")
fmt.Println(mMap.Get("voyager"))
//or as MyMap is a map we could just do
fmt.Println(mMap["voyager"])
}