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
andnil
forerror
).
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 eithererr
oritem
and simplyreturn
. Because we've defined the names we're using for the return values, Go knows to return whatever is assigned to item
anderr
, and because these values start as their empty value (“”
andnil
) we get the same result when we call it.
You can play around with this example on Go playground.
Self taught software developer with 11 years experience excelling at JavaScript/Typescript, React, Node and AWS.
I love learning and teaching and have mentored several junior developers over my career. I find teaching is one of the best ways to solidify your own learning, so in the past few years I've been maintaining a technical blog where I write about some things that I've been learning.
I'm passionate about building a teams culture and processes to make it efficient and satisfying to work in. In many roles I have improved the quality and reliability of the code base by introducing or improving the continuous integration pipeline to include quality gates.