gobyexample
gobyexample copied to clipboard
Proposal: Add named return into functions
There's this thing that I found recently, about returning named values (variables), for example:
import (
"fmt"
"net/url"
"path"
)
// Instead of
func URLGetFilename(rawURL string) (string, error) {
parsedURL, err := url.Parse(rawURL)
if err != nil {
return rawURL, err
}
return path.Base(parsedURL.Path), nil
}
// It's possible to do
func URLGetFilename(rawURL string) (parsedURL string, err error) {
obj, err := url.Parse(rawURL)
if err != nil {
return
}
parsedURL = path.Base(obj.Path)
return
}
Just a silly example to demonstrate the existence of it.
Thanks for the suggestion. Named returns can harm readability in many cases, so I'd like to have a reasonably good example of their usage. There are a couple of examples in Effective Go.
Leaving this issue unassigned and with the help-wanted tag in case someone wants to contribute a PR. Will be happy to review
I agree with @eliben — named returns should only be used when necessary. In your example case, there's no benefit to using them. Also, the naked return should almost never be used, as it makes it very difficult to deduce what values are actually being yielded to the caller. In fact I'm pretty sure your example contains a bug due to it's use: the err returned from url.Parse shadows the named return err!