search

What is the difference between Go's named and anonymous return values?

In Go, a function can have named or anonymous return values. Named return values are declared in the function signature with a type and an identifier, while anonymous return values are declared with just a type. 

Here is an example of a function with named return values:

func divide(x, y float64) (result float64, err error) {
    if y == 0 {
        err = errors.New("division by zero")
        return
    }
    result = x / y
    return
}

Here, the function **divide** takes two float64 arguments and returns a float64 result and an error value. The result value is named **result**, and the error value is named **err**.

We can also define the same function with anonymous return values:

func divide(x, y float64) (float64, error) {
    if y == 0 {
        return 0, errors.New("division by zero")
    }
    return x / y, nil
}

Here, the function **divide** takes two float64 arguments and returns a float64 result and an error value, both of which are anonymous.

The main difference between named and anonymous return values is in how we use them. With named return values, we can assign values to the named variables inside the function body, and they will be automatically returned when the function completes. This can make the code more readable, especially for functions with multiple return values.

With anonymous return values, we need to explicitly return the values using the **return** statement, and we cannot refer to the return values by name inside the function body. This can make the code more concise, especially for functions with simple return values.

In general, the choice between named and anonymous return values depends on the complexity of the function and the desired level of readability and conciseness. For simple functions with one or two return values, anonymous return values can make the code more concise, while for more complex functions with multiple return values, named return values can make the code more readable.

Related Questions You Might Be Interested