Here is an example of a simple type with a method that has a receiver:
package main
import "fmt"
type Message struct {
Content string
}
// value receiver
func (m Message) Display() {
fmt.Println(m.Content)
}
func main() {
msg := Message{"Hello, World!"}
msg.Display() // Calling the method on the Message instance
}
In this example, the Display
method is associated with the Message
type by having a receiver of type Message
. This allows us to call the Display
method on a Message
instance, like msg.Display()
.
Value vs Pointer receiver
- A value receiver will run its operations on a copy of the instance
- While a pointer will operate on the actual instance associated