Go Functions Named Return Values

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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
}

play it on playground

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

play it on playground

Two important things must be noted:

  • The parenthesis around the return values are mandatory.
  • An empty return statement must always be provided.


Got any Go Question?