Skip to content

proposal: spec: permit using nil with type parameters #62487

Closed as not planned
Closed as not planned
@ianlancetaylor

Description

@ianlancetaylor

This is an alternative to #61372. I mentioned it in #61372 (comment), and I'm here pulling it out into a separate proposal.

I propose that we permit using nil with type parameters. Specifically, I propose that we change the language such that

  1. we can assign nil to a variable whose type is a type parameter; it sets the variable to the zero value of its type;
  2. we can compare a value whose type is a type parameter to nil; this is permitted even if the type parameter is not comparable, and == reports whether the value is equal to the zero value of its type.

Background

#61372 aims to solve three problems:

  1. Referring to a zero value in generic code. Today people suggest *new(T), which [@rsc finds] embarrasingly clunky to explain to new users. This comes up fairly often, and we need something cleaner.

  2. Comparing to a zero value in generic code, even for non-comparable type parameters. This comes up less often, but it did just come up in cmp.Or (cmp: add Or #60204).

  3. Shortening error returns: return zero, err is nicer than return time.Time{}, err.

The solution in #61372 is to introduce a new builtin type zero that may be used with any type that does not already have a short name for the zero value.

This proposal addresses the first two points but not the third.


Rationale

I'm concerned that #61372 is overfitting to the current language and creating a solution that makes sense to experienced Go programmers but not to people learning the language for the first time. We already have three names for the zero value: 0, "", nil. Introducing a fourth name, zero, makes sense given where we are but seems confusing for people learning the language for the first time.

Extending the use of zero to all types, as originally proposed and as mentioned by @robpike at #61372 (comment), permits confusion when using a variable p of pointer type: we can write both p == zero and *p == zero, but they mean very different things (as mentioned by @rsc at #61372 (comment)).

Extending the use of nil to all types somewhat exacerbates the problem address by the FAQ in Why is my nil error value no equal to nil?, which has itself been reported as a bug many times despite the FAQ entry (#43643, #44102, #47551, #53768, #54229, #56930, #57292, #59521 among many others).

Extending nil to type parameters only, as proposed here, is imperfect, but it addresses the immediate needs, and to me it seems less imperfect than the other solutions.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions