Tuesday, January 19, 2021

Golang Method Receivers

There are different ways for a method to be assigned to a struct. One of the first thing Golang developers learn is that your method can have a value receiver or a pointer receiver.

Notice below that foo's bar method has a value receiver and accepts zero arguments. Standard stuff. Where it gets interesting is how I call foo.bar in the example main method.

package main

import (
 "fmt"
)

type foo struct {
 msg string
}

func (f foo) bar() string {
 return f.msg
}

func main() {
 receiver := foo{msg: "the value"}
 result := foo.bar(receiver)

 fmt.Println(result)
}