Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: spec: Make empty an alias to struct{} #61156

Closed
flimzy opened this issue Jul 3, 2023 · 2 comments
Closed

proposal: spec: Make empty an alias to struct{} #61156

flimzy opened this issue Jul 3, 2023 · 2 comments

Comments

@flimzy
Copy link
Contributor

flimzy commented Jul 3, 2023

What

I propose we add empty as an alias for the empty struct, struct{}

Example:

map[string]struct{}

could be written as:

map[string]empty

Rationale

struct{} has a couple of very attractive qualities:

  1. It allocates no memory
  2. It semantically indicates an empty value, whereas the most common alternative of bool, frequently makes code less readable, by requiring the reader to consider whether the boolean value is meaningful.

These make the use of struct{} ideal for certain use cases, such as channels that only need to signal an event, but no other information about the event, or a map indicating the existence of a thing. i.e. map[string]struct{}{}

However, struct{} has (at least) two drawbacks that prevent it from being used:

  1. It's a bit awkward to type/read, and subjectively "ugly"
  2. It's not obvious (Based on my purely subjective experience reviewing the code of many new Go developers) to Go newcomers that struct{} is even valid, let alone sometimes desirable for the above reasons

I believe that this addition would improve code readability, as well as encourage the use of constructs like make(chan empty) and make(map[string]empty) in place of make(chan bool) and make(map[string]bool) respectively.

References

  • A quick and lazy search finds over 1200 instances of struct{} in the stdlib (Go 1.20.5)

Naming considerations

empty may not be the best name. In particular, the most common use of the word 'empty' in Go vernacular has been to refer to the empty interface. If this would be seen as conflating with that, perhaps another name would be ideal.

@flimzy flimzy added the Proposal label Jul 3, 2023
@gopherbot gopherbot added this to the Proposal milestone Jul 3, 2023
@fzipp
Copy link
Contributor

fzipp commented Jul 3, 2023

Duplicate of #57825

@flimzy
Copy link
Contributor Author

flimzy commented Jul 3, 2023

Thanks, @fzipp for pointing out the dupe. Closing this one, as it has already been discussed at length.

@flimzy flimzy closed this as completed Jul 3, 2023
@golang golang locked and limited conversation to collaborators Jul 2, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants