Home > Article > Backend Development > Why Does Go Require a "Comma Ok" Pattern for Multiple Value Returns from Map Access?
Multiple Value Return Issue in Go
In Go, returning multiple values from a function is possible using multiple assignment. However, there are some specific requirements that need to be met.
Consider the following code:
func FindUserInfo(id string) (Info, bool) { it, present := all[id] // Valid comma ok assignment pattern return it, present }
This code correctly uses the "comma ok" pattern to obtain multiple values from the map lookup. The present boolean value indicates whether the key was found in the map.
However, the following code is invalid:
func FindUserInfo(id string) (Info, bool) { return all[id] // Invalid, without a comma ok expression }
The compiler flags this as an error, stating that there are multiple values to return, but only one variable is assigned. This error occurs because Go requires explicit assignment of all return values.
To elaborate on this error, the Go language uses a "type equivalence" rule for assignment. In most cases, this means that assigning a value of one type to a variable of another type will result in a compile-time error. However, when accessing a map, an exception is made.
Accessing a map returns a two-value tuple: the underlying value and a boolean indicating whether the key was found. This tuple is commonly assigned to a pair of variables using the "comma ok" pattern.
The Go compiler is specifically designed to allow this pattern, even though it appears to violate the type equivalence rule. As a result, you cannot assign a map value directly to multiple variables without using a comma ok expression.
In your case, you can avoid using temporary variables by ensuring that you always use the comma ok pattern when accessing a map. This ensures that the multiple values are properly assigned and the compiler will not flag any errors.
The above is the detailed content of Why Does Go Require a "Comma Ok" Pattern for Multiple Value Returns from Map Access?. For more information, please follow other related articles on the PHP Chinese website!