Golang in sixty seconds — return multiple values from functions
--
If you’re not familiar with functions, please read this article first.
Golang allows you to return multiple values from a function. Typically this is used for error handling, so you might see a function like this:
func getSecondItem(items []string) (string, error) {
if len(items) < 2 {
return "", errors.New("Too short")
}
return items[1], nil
}
Note that our return types need to be wrapped in brackets when there are more than one of them. In our function above when items is too short we want to return a new error. If the length of items is greater than 1 we want to return the second item. In both cases you’ll notice that we’re returning two things. Because we have defined two return types we have to return two things. In this case we return the empty value for each type (“”
for string
and nil
for error
).
This function could be called like this:
arr := []string{"one"}
item, err := getSecondItem(arr)
fmt.Println(item, err) // Too short
arr = append(arr, "two")
item, err = getSecondItem(arr)
fmt.Println(item, err) // two <nil>
Notice that there are now two values on the left hand side of the assignment
item, err := getSecondItem(arr)
Go also allows you to create named return values when you define a function. These values are created with their empty value for the type, so we can rewrite the above function like this if we wanted:
func getSecondItem(items []string) (item string, err error) {
if len(items) < 2 {
err = errors.New("Too short")
return
}
item = items[1]
return
}
We define the named return values in the same way that we would define the parameters name type, name type
. Now we reassign the value of either err
or item
and simply return
. Because we’ve defined the names we’re using for the return values, Go knows to return whatever is assigned to item
and err
, and because these values start as their empty value (“”
and nil
) we get the same result when we call it.
You can play around with this example on Go playground.
Get Unlimited access to Medium
Buy me a coffee if you enjoyed the article :)