Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
In Go you can write functions that have named result parameters.
Two examples from the spec:
func complexF3() (re float64, im float64) {
re = 7.0
im = 4.0
return
}
func (devnull) Write(p []byte) (n int, _ error) {
n = len(p)
return
}
There are some many advantages on using this syntax.
You don’t have to manually allocate the return variables, as having them named as result types, they are automatically initialized at their zero value for their type when the function begins.
Named return parameters do a very good job as implicit documentation: you know what the function is returning directly from its signature, as naming things help understand the code.
If there are multiple exit points from a function, you don’t need to write all the parameters, just return
(called bare return). You still can list the returned values explicitly, and probably you should, to prevent having code hard to read. As suggested in The Go Programming Language:
[…] with many return statements and several results, bare returns can reduce code duplication, but they rarely make code easier to understand. […] Bare returns are best used sparingly
An example:
func something(n int) (ret int, m string, err error) {
if n == 0 {
err = errors.New("Houston, we have a problem!")
return 0, "", err
}
ret = n + 100
m = "Congratulations"
return ret, m, err
}
or with bare returns:
func something(n int) (ret int, m string, err error) {
if n == 0 {
err = errors.New("Houston, we have a problem!")
return
}
ret = n + 100
m = "Congratulations"
return
}
In both cases the code is cleaner and more readable than
func something(n int) (int, string, error) {
var ret int
var m string
if n == 0 {
err := errors.New("Houston, we have a problem!")
return ret, m, err
}
ret = n + 100
m = "Congratulations"
return ret, m, nil
}
Beware the risk of shadowing a parameter with a new declaration inside the function.
So, when should you use them? When it makes sense to you in the overall design of a program. I’ll let The Go Programming Language reply with a quote:
[…] it’s not always necessary to name multiple results solely for documentation. For instance, convention dictates that a final
bool
result indicates success; anerror
often needs no explanation.
Additional resources:
- https://golang.org/doc/effective_go.html#named-results
- https://golang.org/ref/spec#Return_statements
- https://stackoverflow.com/questions/45239409/empty-return-in-func-with-return-value-in-golang
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More go tutorials:
- Using NGINX Reverse Proxy to serve Go services
- Making a copy of a struct in Go
- The basics of a Go Web Server
- Sorting a map type in Go
- Go pointers in a nutshell
- Go Tags explained
- Go Date and Time Formatting
- JSON processing with Go
- Go Variadic Functions
- Go Strings Cheat Sheet
- The Go Empty Interface Explained
- Debugging Go with VS Code and Delve
- Named Go returns parameters
- Generating random numbers and strings in Go
- Filesystem Structure of a Go project
- Binary Search Algorithm Implemented in Go
- Using Command Line Flags in Go
- GOPATH Explained
- Build a Command Line app with Go: lolcat
- Building a CLI command with Go: cowsay
- Using Shell Pipes with Go
- Go CLI tutorial: fortune clone
- List the files in a folder with Go
- Use Go to get a list of repositories from GitHub
- Go, append a slice of strings to a file
- Go, convert a string to a bytes slice
- Visualize your local Git contributions with Go
- Getting started with Go CPU and memory profiling
- Solving the "does not support indexing" error in a Go program
- Measuring execution time in a Go program
- Building a Web Crawler with Go to detect duplicate titles
- Go Best Practices: Pointer or value receivers?
- Go Best Practices: Should you use a method or a function?
- Go Data Structures: Set
- Go Maps Cheat Sheet
- Generate implementations for generic types in Go
- Go Data Structures: Dictionary
- Go Data Structures: Hash Table
- Implement Events Listeners in Go through Channels
- Go Data Structures: Stack
- Go Data Structures: Queue
- Go Data Structures: Binary Search Tree
- Go Data Structures: Graph
- Go Data Structures: Linked List
- The complete guide to Go Data Structures
- Comparing Go Values
- Is Go object oriented?
- Working with a SQL Database in Go
- Using environment variables in Go
- Go tutorial: REST API backed by PostgreSQL
- Enabling CORS on a Go Web Server
- Deploying a Go Application in a Docker Container
- Why Go is a powerful language to learn as a PHP developer
- Go, remove the io.Reader.ReadString newline char
- Go, how to watch changes and rebuild your program
- Go, count the months since a date
- Accessing HTTP POST parameters in Go