Methods on Structs
Value receivers vs pointer receivers
What Is a Method?
A method is a function with a receiver argument. The receiver appears between the func keyword and the method name, binding the function to a type.
Value Receiver
A value receiver receives a copy of the struct. Use when the method doesn't need to mutate state:
package main
import "fmt"
type Circle struct{ Radius float64 }
func (c Circle) Area() float64 {
return 3.14159 * c.Radius * c.Radius
}
func main() {
c := Circle{Radius: 5}
fmt.Printf("%.2f\n", c.Area()) // 78.54
}