Skip to content

proposal: Go 2: use an identifier other than nil for uninitialized interfaces #24682

Closed
@pcostanza

Description

@pcostanza

This is a variation of #21538 with a very important difference (see below). It's also related to #22729 and #24635.

It's confusing that nil can be used both as a value to represent an uninitialized interface, and as a value for the pointer that an interface is initialized with. This is a stumbling block for people new to Go, but also trips up experienced developers every now and then.

Proposal: use a value other than nil for uninitialized interfaces. To avoid adding new pre-defined identifiers, the value could be syntactically represented as {}, for example, but it may also be ok to introduce a new identifier, like null or nilinterface, or some such. This means testing for an uninitialized interface would have to be expressed like this:

var v interface{}
...
if v != {} {
   ...
}

With this proposal, tests against nil (like in v != nil) are not allowed anymore. This proposal explicitly does not suggest to add a way for testing for typed nil pointers stored in interfaces in any way. (If you prefer such a feature, refer to one of the other proposals mentioned above, or submit a separate, potentially complementary proposal.)

Rationale: A lot of people seem to be strongly opposed to adding a way to allow for testing for typed nil pointers being stored in an interface variable other than through the reflect package, and strongly encourage people to call methods instead that are supposed to handle nil pointers gracefully. I still strongly believe the language is improved if interface variables are simply not comparable to the nil identifier anymore at all to make that distinction even more explicit, and ensure that developers don't falsely believe they compared to any other possible meaning of nil.

This proposal implies a change that is not backwards compatible, but it should be easy to write a tool that automatically converts programs since a type checker should be able to detect the relevant cases.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions