functions

func add(a, b int) int {
	return a + b
}

One signature, one return value Go also allows several returns, which is how errors travel

Multiple returns

func parse(s string) (int, error) {
	return strconv.Atoi(s)
}

Callers handle both values Ignoring an error with _ is a choice, not a default

Variadic

func joinAll(parts ...string) string {
	return strings.Join(parts, " ")
}

Variadic parameters collect a list Use them for genuinely optional repetition, not as a substitute for a slice

Closures

counter := 0
inc := func() int {
	counter++
	return counter
}

A closure captures the variable, not its value at creation In a loop before Go 1.22 that caused the classic repeated value bug Current language versions fixed the loop variable semantics Old tutorials still teach the workaround, do not copy them blindly

Next

Errors in 05 errors

Posted