"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Can't Go Functions Return Multiple Values Directly?

Why Can't Go Functions Return Multiple Values Directly?

Published on 2024-11-20
Browse:159

Why Can't Go Functions Return Multiple Values Directly?

Go Return Multiple Values Issue

When attempting to return multiple values in Go, it may seem confusing why certain syntax is valid while others are not. To illustrate this, consider the following two code snippets:

func FindUserInfo(id string) (Info, bool) {
    it, present := all[id]
    return it, present
}

The first code snippet is valid and returns both the Info and bool values. However, the second snippet is invalid:

func FindUserInfo(id string) (Info, bool) {
    return all[id]
}

This raises the question of why the first snippet is valid and the second is not. Additionally, one may wonder if there is a way to avoid using temporary variables like it and present.

Explaining the "Comma Ok" Pattern

The key to understanding this behavior lies in the "comma ok" pattern. In Go, when accessing a map, the result is a pair of values: the value associated with the key and a boolean indicating whether the key exists in the map. This is often used to differentiate between a missing key and a zero value.

In the first code snippet, the all[id] expression returns a pair of values, which are assigned to it and present. The return statement then returns these values.

Compiler Considerations

The compiler plays a role in determining whether a multi-value assignment is valid. If the function returns multiple values but the recipient on the left-hand side has only one variable, the compiler will issue an error. This is because the compiler expects the number of values returned to match the number of variables receiving them.

In the case of the second code snippet, the return all[id] expression only returns one value, which is incompatible with the two variables on the left-hand side. Hence, the compiler reports an error.

Avoiding Temporary Variables

Unfortunately, there is no way to avoid using temporary variables when returning multiple values in a Go function. This is because the compiler requires the number of returned values to match the number of variables receiving them. However, it is possible to minimize the usage of temporary variables by using named return values or returning a struct.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3