Home > Article > Backend Development > Why Does Go Require Explicit Assignment for Multi-Value Returns?
Go Multi-Value Return Issue
In Go, returning multiple values from a function is a common practice, but certain syntax limitations can arise. Let's explore why the following code snippets behave differently:
Valid Code:
func FindUserInfo(id string) (Info, bool) { it, present := all[id] return it, present }
Invalid Code:
func FindUserInfo(id string) (Info, bool) { return all[id] }
Reason for Invalid Syntax:
The second code snippet attempts to return two values directly from the map lookup all[id]. However, Go requires explicit assignment of multiple return values.
"Comma Ok" Pattern:
The Go "Comma Ok" pattern is a mechanism to extract a value and a boolean indicator (usually named ok) from accessing a map key. This pattern is supported for maps, channels, and type assertions.
In your case, it is the retrieved value, and present is a boolean indicating whether the key exists in the map. The assignment with comma separation it, present := all[id] implicitly uses this pattern.
Understanding Unpack Method:
Internally, Go uses the unpack method to handle multiple value assignments. This method determines if the assignment is a "comma ok" case based on the mode of the operands (e.g., map indexing, channel value, type assertion).
By default, the unpack method only allows comma ok assignments when doing assignments with two variables on the left-hand side. This restriction is set in the Checker.initVars() method.
Conclusion:
The "comma ok" pattern in Go enables retrieving multiple values from maps, channels, and type assertions. However, explicit assignment of return values is required, and the compiler restricts comma ok assignments to scenarios where two variables are present on the left-hand side.
The above is the detailed content of Why Does Go Require Explicit Assignment for Multi-Value Returns?. For more information, please follow other related articles on the PHP Chinese website!