Receiver types let you attach functions to your own data types. This helps organize code and work with data easily.
0
0
Receiver types in Go
Introduction
When you want to add behavior to a custom data type, like a struct.
When you want to change the data inside a struct from a function.
When you want to read data from a struct without changing it.
When you want to group related functions together for clarity.
When you want to use methods on values or pointers depending on your needs.
Syntax
Go
func (receiver ReceiverType) MethodName(params) returnType {
// method body
}The receiver is like a special input that the method uses to access the data.
ReceiverType can be a value type (e.g., MyStruct) or a pointer type (e.g., *MyStruct).
Examples
This method uses a value receiver. It can read data but changes won't affect the original.
Go
func (p Person) Greet() string {
return "Hello, " + p.Name
}This method uses a pointer receiver. It can change the original data inside the struct.
Go
func (p *Person) SetName(newName string) {
p.Name = newName
}Sample Program
This program shows two methods on Person. One reads the name and says hello. The other adds one to the age using a pointer receiver.
Go
package main import "fmt" type Person struct { Name string Age int } // Value receiver: reads data func (p Person) Greet() string { return "Hello, " + p.Name } // Pointer receiver: changes data func (p *Person) HaveBirthday() { p.Age++ } func main() { person := Person{Name: "Alice", Age: 30} fmt.Println(person.Greet()) person.HaveBirthday() fmt.Println("Age after birthday:", person.Age) }
OutputSuccess
Important Notes
Use pointer receivers when you want to modify the original data.
Use value receivers when you only need to read data and keep the original safe.
Pointer receivers avoid copying the whole struct, which can be faster for big data.
Summary
Receiver types let you add methods to your own types.
Value receivers get a copy; pointer receivers get the original to change.
Choose receiver type based on whether you want to modify data or not.