What benefits arise from naming a function's return parameter(s)?
func namedReturn(i int) (ret int) { ret = i i += 2 return } func anonReturn(i int) int { ret := i i += 2 return ret }
Goal: Parameters and return values allow students to write programs that are more organized and cleaner. Naming functions helps students write programs that read more like descriptions of what they do, and they also help students reuse code.
Generally, a return value is used where the function is an intermediate step in a calculation of some kind. You want to get to a final result, which involves some values that need to be calculated by a function.
The parameter is a string in which you will count the words. The argument is any string you pass to your function when you call it. The return value is the number of words.
A return value is a result of the function's execution. It can be returned to the block of code that called the function, and then used as needed. Parameters are the necessary input for a function to be executed and produce a result. Parameters are variables defined by name.
There are some benefits to naming them:
There are also downsides, mainly that it's easy to accidentally shadow them by declaring a variable of the same name.
Effective Go has a section on named result parameters:
The return or result "parameters" of a Go function can be given names and used as regular variables, just like the incoming parameters. When named, they are initialized to the zero values for their types when the function begins; if the function executes a return statement with no arguments, the current values of the result parameters are used as the returned values.
The names are not mandatory but they can make code shorter and clearer: they're documentation. If we name the results of nextInt it becomes obvious which returned int is which.
func nextInt(b []byte, pos int) (value, nextPos int) {
[...]
Another special use for a named return variable is to be captured by a deferred function literal. A trivial illustration:
package main import ( "errors" "fmt" ) func main() { fmt.Println(f()) } var harmlessError = errors.New("you should worry!") func f() (err error) { defer func() { if err == harmlessError { err = nil } }() return harmlessError }
Output is <nil>
. In more practical scenarios, the deferred function may handle panics, and may modify other return values besides an error result. The magic in common though, is that the deferred literal has a chance to modify the return values of f after f is terminated, either normally or by panic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With