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.
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.
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.
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.
The above is the detailed content of Why Can't Go Functions Return Multiple Values Directly?. For more information, please follow other related articles on the PHP Chinese website!