Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Add named return into functions #368

Open
rafaelbreno opened this issue May 12, 2021 · 2 comments
Open

Proposal: Add named return into functions #368

rafaelbreno opened this issue May 12, 2021 · 2 comments

Comments

@rafaelbreno
Copy link

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.

@eliben
Copy link
Collaborator

eliben commented Nov 23, 2021

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

@peterbourgon
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants