Named return values are exactly what they sound like. Instead of just having a return Type on your function, you can actually name the value that is being returned. Let me show you with a simple example:
func sumValues(vals []int) (total int) {
for _, v := range vals {
total += v
}
return
}
The benefit is primarily for readability. You can be clear with what a function should return. You may notice a few things in the code block above that looks strange:
total
variable looks to be undefined. This is because the variable actually gets created with a nil
value (in this case 0
) by having it as a named return value.total
. It's recommended that you only use naked returns on small functions as you lose readability with longer functions.I find named return values quite useful for things like the example above where you remove the need to define a nil
value variable at the start of the function. You can try the above example here.
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.