Skip to content

proposal: Go 2: allow second argument to close as alternative to futures #23197

Closed
@DeedleFake

Description

@DeedleFake

I was reading through #17466 and I realized that future-style functionality already exists with channels via close(). The only real difference is that a closed channel always returns a zero value of its element type. Therefore, I propose adding a second, optional argument to close() which, if specified, causes receives on the channel to return the value given, rather than the zero value.

For example, the following would print 3 twice:

c := make(chan int)
close(c, 3)
println(<-c)
println(<-c)

I fiddled around with the runtime and compiler in an attempt to get it working myself as an experiment to see how viable it is. I'm not particularly familiar with a lot of the internals, but I managed to get it working in the runtime with minimal effort. I had a bit more trouble with getting the compiler to accept a second argument to close(), but I know that that's plausible as there are other built-in functions that do similar things.

Advantages

  • Doesn't break Go 1 compatibility guarantee. It would require a tweak to the internal structure of channels, but that's not something that's guaranteed to stay the same, so that should be fine.
  • Provides 1:N one-time broadcasting capability, as futures do, as well as the ability to receive the 'sent' value multiple times from the same channel. It basically makes channels act exactly like futures, without requiring any new types or standard library API.

Disadavantages

  • close() is a bit awkwardly named for this type of thing, even if it does make sense in terms of it being a channel. If this is accepted, it might be a good idea to do something a bit different for Go 2.

I'm sure there are other problems, but that's why I'm proposing it. I'd originally posted this as a comment on the previously referenced issue, but it's quite different from what was proposed there and no one responded, so I decided to make it a separate proposal.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions