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)