Skip to content

proposal: spec: define _ on rhs as zero value #19642

Closed
@dans-stuff

Description

@dans-stuff

Currently, _ only has behaviour on the LHS.

I would like to propose giving it meaning on the RHS as meaning "zero value". This has two main areas of effect.

First, when returning from a function with multiple return values, you can omit the zero-value allocation. For example,

func GetString() (string, error) { return _, errors.New("nostring") }

Understandably you can use named returns as well, but that is less than ideal if you use the named return value as a "scratch space" before deciding to return zero anyway. For example, when building some struct, such as a Request, you might use a named return to build it and, later in the function, come across an error which invalidates your scratch space, in which case you would want to return a zero-value instead of a half-initialized struct with some garbage inside.

Second, when you want to reset a struct, such as when using a pool, you could use _ to restore it to a zero-value.

func Pool() func() (User, func()) {
	var pool User
	// in reality, use some pooling mechanics
	return func() (u User, reset func()) {
		return pool, func() {
			// zero out and return this copy to the pool
			pool = _
		}
	}
}

nil would remain the correct way to create the zero-value for reference types.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeLanguageChangeSuggested changes to the Go languageNeedsDecisionFeedback is required from experts, contributors, and/or the community before a change can be made.Proposalv2An incompatible library change

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions