Functions and Methods
Functions, methods, and call patterns. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Search across all documentation pages
Functions, methods, and call patterns. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Common (value, error) pattern.
func div(a, b int) (int, error) {
if b == 0 { return 0, errors.New("div0") }
return a / b, nil
}
q, err := div(10, 2)
q // 5
// err == nilNaked return uses named results - use sparingly.
func split(s string) (head, tail string) {
head, tail = s[:1], s[1:]
return
}
h, t := split("ab")
h // "a"
// t == "b"Value or pointer receivers.
type Counter struct{ N int }
func (c *Counter) Inc() { c.N++ }
c := Counter{}
c.Inc()
c.N // 1Trailing ...T collects args as slice.
func sum(xs ...int) int {
n := 0
for _, x := range xs { n += x }
return n
}
sum(1, 2, 3) // 6Deferred calls run LIFO at return.
// defer fmt.Println(1)
// defer fmt.Println(2)
// prints 2 then 1Functions are values.
add := func(a, b int) int { return a + b }
add(2, 3) // 5Closures capture variables by reference.
n := 0
inc := func() { n++ }
inc(); inc()
n // 2Package init runs before main.
// func init() { /* setup */ }
// no args, no returns; may have multiple per fileSlices pass header by value; backing array shared.
func set(s []int) { s[0] = 9 }
x := []int{1}
set(x)
x[0] // 9Higher-order functions.
func makeAdder(k int) func(int) int {
return func(n int) int { return n + k }
}
makeAdder(10)(5) // 15import _ "pkg" for init only.
// import _ "net/http/pprof"
// registers handlers via initType.Method as function.
type T int
func (t T) V() int { return int(t) }
T.V(T(3)) // 3Bound method as func.
c := Counter{N: 1}
f := c.Inc
f()
c.N // 2Pass slice as variadic with ....
xs := []int{1, 2}
sum(xs...) // 3Recover only in deferred funcs.
func safe() (ok bool) {
defer func() {
if r := recover(); r != nil { ok = false }
}()
panic("x")
}
// safe() recoversStack versions: Go 1.26.x · chi/gin/echo latest (verify at build)
Reviewed by Chris St. John·Last updated Jul 18, 2026