Multiple Return Values in Go
Multiple Return Values
34
In Go, it is possible for a function to return multiple values. This feature is very useful as it allows us to return multiple results from a function without the need for additional data structures like tuples or lists.
To return multiple values from a function, we need to specify the return types separated by commas.
For example, the following function returns an integer and a boolean value:
func divide(a, b int) (int, bool) { if b == 0 { return 0, false } else { return a / b, true } }
Here, the first return value is the result of the division, and the second value is a boolean flag indicating whether the division was successful or not (i.e., whether the second argument was zero or not).
We can also use multiple return values in a function call, like this:
result, ok := divide(10, 2)
This will assign the first return value to result
and the second to ok
. If the division was successful, ok
will be set to true
.
Multiple return values can be very convenient in many situations, for example when writing error-prone code. We can use one value to return the result of a computation, and another one to return an error code or error message if something went wrong.
March 27, 2023