Skip to content

go compiler to raise an error if function not explicitly return nil with return value of interface type signature #46627

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

Closed
ideawu opened this issue Jun 7, 2021 · 2 comments

Comments

@ideawu
Copy link

ideawu commented Jun 7, 2021

Many known that the famous nil != nil trap when using interface variable. The Golang FAQ "Why is my nil error value not equal to nil?" says:

To return a proper nil error to the caller, the function must return an explicit nil:

func returnsError() error {
	if bad() {
		return ErrBad
	}
	return nil
}

And the FAQ show an bad(wrong) coding paradigm when a function with return value of interface type signature:

func returnsError() error {
	var p *MyError = nil
	if bad() {
		p = ErrBad
	}
	return p // Will always return a non-nil error.
}

So, would it be a good idea for go compiler, to discover these kind of bad code and treats as a programming error(or a friendly warning) that must be fixed? Whenever a function has return value of interface signature, it must explicitly has at least one line of

return nil
@seankhliao
Copy link
Member

Consider any non error interface, there's no guarantee that valid code will always have a path that returns nil, eg:

func New() io.Reader {
    return &myStruct{}
}

And in general, the false positive rate is going to be too high for both the compiler or go vet to do anything about it.

@timothy-king
Copy link
Contributor

And in general, the false positive rate is going to be too high for both the compiler or go vet to do anything about it.

Staticcheck has a checker for this SA4023. IMO there is room for go vet to potentially warn about this in the future. The false positive rate would need to be quite low. (Agree that an error in the compiler seems too likely to have false positives on valid programs.)

@golang golang locked and limited conversation to collaborators Jun 15, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants