Methods let you do actions with data stored in a type. Understanding how method calls work helps you write clear and correct programs.
Method call behavior in Go
func (receiver Type) MethodName(params) returnType {
// method body
}The receiver is like the object the method works on.
Receivers can be values or pointers, which affects if the method can change the original data.
Person.type Person struct {
name string
}
func (p Person) Greet() string {
return "Hello, " + p.name
}Person data.func (p *Person) ChangeName(newName string) {
p.name = newName
}Person variable.p := Person{name: "Alice"}
fmt.Println(p.Greet())
p.ChangeName("Bob")
fmt.Println(p.Greet())This program shows how methods with value and pointer receivers behave differently. The Increment method changes the original Counter because it uses a pointer receiver.
package main import "fmt" type Counter struct { count int } // Method with value receiver: cannot change original func (c Counter) Display() { fmt.Println("Count is", c.count) } // Method with pointer receiver: can change original func (c *Counter) Increment() { c.count++ } func main() { c := Counter{count: 5} c.Display() // prints 5 c.Increment() // increases count c.Display() // prints 6 }
Using a pointer receiver lets the method change the original data.
Using a value receiver means the method works on a copy and cannot change the original.
Go lets you call pointer methods on values and value methods on pointers; it handles conversion automatically.
Methods are functions tied to a type using receivers.
Pointer receivers allow methods to modify the original data.
Value receivers work on copies and cannot change the original data.