Skip to content

proposal: spec: drop new(int) in favor of &int{} #20446

@alercah

Description

@alercah

This is sort of spawning out of #19642, and may be related to its resolution.

Currently, struct types (and, less commonly, array, slice, and map types) can have a pointer to a zero value constructed in two different ways: new(T) and &T{}. I've never seen a style guide recommending one or the other, but the latter is more clear next to &T{foo}.

Having two ways to do something isn't ideal, so one potential solution is to allow composite literals for all types (with one possible exception I'll get to). For any type for which Go 1 does not allow composite literals (numeric, boolean, function, interface, channel, and pointer types), the literal must be empty and yields the zero value. So instead of writing new(int), you would write &int{}.

If this is done, the new builtin becomes redundant. We can therefore remove it from the language to simplify. I'm not sure this is necessarily a good idea, but it would remove the duplication.

The only issue is pointer types. Under this proposal, I think that *T{} is ambiguous between "a pointer to a zero T" and "a nil pointer to T" (I frequently mistype *T{} for &T{}). I'm not sure the best resolution for this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions