Skip to content

proposal: builtin: zero function #60695

Closed
@nathan-cormier

Description

@nathan-cormier

Presently the language offers a few ways to get the Zero Value of a type, but it would make code more readable to have a canonical way to accomplish this.

This proposal would like to add a new builtin function:

func zero(Type) Type

This is quite similar to the new builtin, but returns an instance of Type instead of a Pointer-To-Type.

This would serve as shorthand for some of the many ways to get a zero value. For example one could do:

return zero(MyType)

Instead of:

var z MyType
return z

Or instead of:

return *new(MyType)

It also makes comparison with zero values rather concise and self-documenting:

if val == zero(MyType) {

This is more readable than either of these existing tests:

// this requires using the reflect package
if reflect.ValueOf(val).IsZero() {
// this means the same but doesn't signal intent as clearly
if val == *new(MyType) {

And of course, just like new this would play nicely with generics:

func example[T any]() T {
  // do something that returns an error...
  if err != nil {
    return zero(T)
  }
  //...
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions