Skip to content

proposal: spec: add kind-specific nil predeclared identifier constants #22729

Open

Description

@ianlancetaylor

A common error for people new to Go is misunderstanding that a interface that is not nil can contain a nil pointer. This is one of the most commonly cited entries in the Go FAQ: https://golang.org/doc/faq#nil_error. A quick search shows at least 24 threads on golang-nuts discussing this, even though it is already in the FAQ.

It is not new to observe that one of the causes of this common mistake is that nil is overloaded. Since changing that would not be backwards compatible, I propose the following changes.

  1. We add six new predefined identifiers: nilptr, nilinterface, nilslice, nilchan, nilfunc, nilmap. These new identifiers are untyped constants that only resolve to a certain kind, much as 1.1 is an untyped constant that only resolves to a float or complex type. nilptr may be used as the zero value for any pointer type, nilinterface may be used as the zero value for any interface type, and so forth. An attempt to use, for example, nilptr in an assignment or comparison with a variable or value that is not a pointer type is invalid.

  2. We add a vet check that warns about any comparison of a value of any type with plain nil. We encourage people to change x == nil to x == nilinterface or x == nilptr or whatever is appropriate. Since initially this vet check will trigger all the time, we can not turn it on when running go test. It could be on by default when running go vet.

  3. At this point people who run go vet will no longer make the common mistake. If v is a value of interface type, then writing v == nilptr will be a compilation error. Writing v == nilinterface will not cause people to erroneously think that this is testing whether v contains a nil pointer.

  4. In some later release, we turn on the vet check when running go test.

  5. If we are ever willing to make a backward incompatible change, we can make v == nil a compilation error rather than simply being a vet error.

Something to consider is that one could imagine permitting v == nilptr when v has an interface type, and having this be true if v is not nilinterface, if v holds a value of pointer type, and if the pointer value is nilptr. I don't know that this is a good idea, and I'm not proposing it. I'm only proposing the above.

Activity

  1. added
    v2An incompatible library change
    LanguageChangeSuggested changes to the Go language
    on Nov 15, 2017
  2. added this to the Proposal milestone on Nov 15, 2017
  3. cespare commented on Nov 15, 2017

    @cespare
    Contributor

    One consequence of this would be that the extremely common if err != nil { ... } would be significantly longer: if err != nilinterface { ... }.

  4. ianlancetaylor commented on Nov 15, 2017

    @ianlancetaylor
    ContributorAuthor

    @cespare Very valid point.

  5. bradfitz commented on Nov 15, 2017

    @bradfitz
    Contributor

    I'd be happier with something in the middle: only adding nilinterface, but naming it none or something shorter. I don't think nilmap, nilslice, etc generate enough confusion.

  6. ianlancetaylor commented on Nov 15, 2017

    @ianlancetaylor
    ContributorAuthor

    @bradfitz It sounds like you are suggesting that we move toward a different name for the zero value of an interface type, but keep the general overloading of nil for non-interface types. Does that sound right?

    I don't really see none as conveying the right idea, but I'm having trouble coming up with a good name. We could try nili or inil, but those might be too close to nil. Maybe empty? I hope someone else has a better idea.

    (C++ has a similar confusion in which 0 is the zero value for both integers and pointers, with the preprocessor macro NULL often being used in code. In C++ this has now been resolved by preferring the new keyword nullptr as the pointer zero value.)

  7. bradfitz commented on Nov 15, 2017

    @bradfitz
    Contributor

    It sounds like you are suggesting that we move toward a different name for the zero value of an interface type, but keep the general overloading of nil for non-interface types. Does that sound right?

    Yes.

    Maybe empty?

    I like empty.

    Seeing lots of if err != empty { ... } is still pretty verbose, though.

  8. cznic commented on Nov 15, 2017

    @cznic
    Contributor

    Maybe empty?

    empty is nice, and it would be enough to predeclare it in the universe scope without breaking any existing Go1 program.

    package main
    
    import (
    	"fmt"
    	"io"
    )
    
    var empty interface{}
    
    func main() {
    	var w io.Writer
    	fmt.Println(w == empty)
    }

    Playground

  9. cznic commented on Nov 15, 2017

    @cznic
    Contributor

    it would be enough to predeclare it in the universe scope without breaking any existing Go1 program.

    Which is actually what the proposal says, but I noticed that only now, mea culpa 👎

  10. davecheney commented on Nov 15, 2017

    @davecheney
    Contributor

    @ianlancetaylor thank you for raising this issue. I think this proposal adds a lot of complexity to solve a single issue, returning a typed nil. What about just making a typed nil equal to nil? It is after all what the author of the check intended.

  11. bradfitz commented on Nov 15, 2017

    @bradfitz
    Contributor

    What about just making a typed nil equal to nil?

    That breaks valid code.

  12. neild commented on Nov 15, 2017

    @neild
    Contributor

    If interface{}((*T)(nil)) == nil, how do you test to see if an interface value is zero? I also think changing this equality might be superficially more intuitive, but is more confusing when you dig into it.

    Instead of changing the name of a zero-valued interface, it would also be possible to change the name of a zero-valued pointer. null, nullptr, or maybe just 0.

  13. davecheney commented on Nov 15, 2017

    @davecheney
    Contributor
  14. 39 remaining items

  15. andig commented on Apr 10, 2020

    @andig
    Contributor

    This is a little off-topic, but since https://golang.org/doc/faq#nil_error was mentioned I feel it's not precise enough:

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

    It's a good idea for functions that return errors always to use the error type in their signature (as we did above) rather than a concrete type such as *MyError, to help guarantee the error is created correctly.

    It seems that the bad (first) example is "use(ing) the error type in their signature" as advised, yet still broken. It should not only use the error type but also return the nil interface instead of a differently-typed nil (if that's the correct wording).

  16. rogpeppe commented on Aug 24, 2020

    @rogpeppe
    Contributor

    @griesemer wrote:

    It also would be a mistake to equate a test of (interface) x == nil as a test that ignores typed nils (as @davecheney suggested). @bradfitz already pointed out that it would not be backward-compatible. But it's actually important that we have this facility in the first place: A common idiom in Go is to define data types whose zero values are values that are ready to use. It can make a lot of sense to define a pointer type whose zero value (nil) is a ready-to use value. It may have methods that work with nil receivers. Such a type may even implement the error interface and thus represent a valid error (and we might not know about it if such a type is defined in some external library). It is imperative that in such a case the test err == nil doesn't yield true. Perhaps far-fetched a scenario for an error type, but not so much for other situations.

    I've been thinking about this for a long time, and while I buy the theoretical argument, I'm still not entirely convinced.
    I haven't yet seen many significant cases where this property is used to advantage.

    One point in favour of disallowing typed nils as valid receivers: the pointer method set also contains the value method set, but if you happen to call a value method when the pointer is nil, you'll get a panic, so that property isn't as useful as it could be. Passing the zero value is one possible way of fixing that, but disallowing nil receivers would be another. If you disallow nil receivers, then perhaps it's reasonable to change a typed nil pointer into an untyped nil when converting to an interface. The problem is much less acute for slices, channels and maps, so perhaps they could be left as is.

    But as @ianlancetaylor points out in the above-mentioned issue, doing this would change the behaviour of existing code, which probably rules it out as a language change.

  17. tandr commented on Aug 24, 2020

    @tandr

    Would completely disallowing a naked (uncasted) nils in comparisons solve this? Like, enforce a rule that nil cannot be naked, it has to be dressed in a type wrapper. (if only for "complex" type comparisons at the beginning) go vet should be able to help with transition.

    Sorry, I don't remember if it was suggested and declined as "too much existing code affected".

  18. ianlancetaylor commented on Aug 24, 2020

    @ianlancetaylor
    ContributorAuthor

    @tandr Anything that requires us to rewrite if err != nil is a non-starter. (That is also a problem with this proposal.)

  19. earthboundkid commented on Aug 24, 2020

    @earthboundkid
    Contributor

    The options are:

    • Add a new identifier for interfaces (+slice +map +channel?) and leave nil pointers alone
    • Add a new identifier for pointers (+slice +map +channel?) and leave nil interfaces alone
    • Add two new identifiers (or more with slice/map/channel)

    Whichever is done, for backwards compatibility reasons p == nil and err == nil can probably never be changed, but you could add a lint check + rewriter to used the preferred one.

    On identifiers, my two cents are that nilinterface is too long to type regularly. (interface{} is already long enough, and you don't have to type it that often.) null is good on its own, but probably too close to nil if we have both in the language. none seems fine. So, I lean towards, just add none for interfaces and get a rewriter for err == nil to err == none. You could also make none valid for map/slice/chan, but I don't think that solves a real problem, so I would lean against it.

  20. andig commented on Aug 24, 2020

    @andig
    Contributor

    To pick up thw comment by @tandr: why to we need the ability to invoke methods on a nil value at all? I think I understand why its technically possible and permitted by the language as-is, but is it necessary for any purpose?

  21. xuanswe commented on Aug 11, 2023

    @xuanswe

    I did not read all comments in this very long topic, sorry for that.
    I am also new to this language, so sorry if I don't understand the details.

    But is that the same story as Dart?

    Dart 1: no null-safety
    Dart 2: null-safety feature is optional. migration-tool is provided.
    Dart 3: null-safety feature is a must

    100% sound null safety
    Dart 2.12 introduced null safety more than two years ago. In Dart 2.12, users needed to enable null safety with a pubspec setting. In Dart 3, null safety is built in; you cannot turn it off.

    Why don't we apply this successful story to Go?

  22. ianlancetaylor commented on Aug 11, 2023

    @ianlancetaylor
    ContributorAuthor

    @xuan-nguyen-swe This issue doesn't have anything to do with null safety. That is a completely different topic. For null safety see, for example, #28133.

  23. xuanswe commented on Aug 11, 2023

    @xuanswe

    @ianlancetaylor thanks for redirecting me to the correct topic!
    I am new to Go, so please apologies to me if I misunderstood something.

  24. changed the title [-]proposal: Go 2: add kind-specific nil predeclared identifier constants[/-] [+]proposal: spec: add kind-specific nil predeclared identifier constants[/+] on Aug 6, 2024
  25. added
    LanguageChangeReviewDiscussed by language change review committee
    and removed
    v2An incompatible library change
    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.
    on Aug 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions