Skip to content

spec: add untyped builtin zero #61372

Closed
Closed
@rsc

Description

@rsc

I propose to add a new predeclared identifier zero that is an untyped zero value. While nil is an untyped zero value restricted to chan/func/interface/map/slice/pointer types, zero would be an untyped zero value with no such restrictions.

The specific rules for zero mimic nil with fewer restrictions:

  • zero is assignable to any variable of any type T that does not already have a short zero (0, "", nil), including when T is a type parameter with constraint any.
  • A value of any type T may be compared to zero when it cannot already be compared to a short zero (0, "", nil), again including when T is a type parameter with constraint any.

That's it. That's all the rules.

Note that assignability includes function arguments and return values: f(zero) and return zero, err are valid.

See CL 509995 for exact spec changes.


This proposal addresses at least three important needs:

  1. Referring to a zero value in generic code. Today people suggest *new(T), which I find 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.

More generally, the zero value is an important concept in Go that some types currently have no name for. Now they would: zero.

Because zero is not valid anywhere 0, "", or nil are valid, there will be no confusion about which to use.


I'm not claiming any originality in this proposal. Others have certainly suggested variants in the past, in quite long discussions. I'm not aware of any precise statement of the exact rules above, but I won't be surprised if one exists.

A brief comparison with earlier proposals:

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions