Principal
What is a receiver in Go, what types are there, and what are they used for?
sobes.tech AI
Answer from AI
In Go language, a receiver is a method parameter that indicates which type it belongs to. The receiver allows defining methods for a specific type (struct or other user-defined type).
There are two types of receivers:
- Value receiver — the method receives a copy of the value of the type. Changes inside the method do not affect the original.
- Pointer receiver — the method receives a pointer to the value. It allows modifying the object's state and avoids copying large structures.
Receivers are used to implement methods, enabling behavior for types, supporting interfaces, and organizing code in a more object-oriented manner.
Example:
package main
import "fmt"
type Counter struct {
count int
}
// Method with a pointer receiver modifies the state
func (c *Counter) Increment() {
c.count++
}
// Method with a value receiver does not modify the original
func (c Counter) Display() {
fmt.Println(c.count)
}
func main() {
c := Counter{count: 5}
c.Increment() // will change c.count
c.Display() // will print 6
}
Thus, receivers are a way to associate methods with types in Go.