Essential Go Functions  Edit on GitHub      File Issue

Named return values

Return values can be assigned to a local variable.

An empty return statement can then be used to return their current values. This is known as “naked” return.

Naked return statements should be used only in short functions as they harm readability in longer functions:

func inverse(v float32) (reciprocal float32) {
	if v == 0 {
		return
	}
	reciprocal = 1 / v
	return
}

// function can return multiple values
func split(sum int) (x, y int) {
	x = sum * 4 / 9
	y = sum - x
	return
}

func main() {
	fmt.Printf("inverse(5)=%.2f\n", inverse(5))
}
inverse(5)=0.20

Two important things must be noted:

  ↑ ↓ to navigate     ↵ to select     Esc to close