Proposal: return sugar

I am looking for examples that would break current golang code so I can make a proper proposal. That’s my first priority. Second, the convincing part which is going to be really really hard to do :slight_smile:

Optional auto return values as soon as there are assigned and none of them is nil using the following syntax?

// returns err if not nil
func example()  error {
     dat, !err := ioutil.ReadFile("/tmp/dat")
// returns (x, y) if none of them is nil
func split() (int, int) {
    !(x, y) := 6, 5

It’s not that this would break any code, but that this is an addition to Go 's syntax. You’re proposing a new form of assignment, and Go already has too many of those.

My advice is to drop this proposal, error handling sugar has been debated many times over the last 7 years, and the chance of a change at this stage is vanishingly remote.

1 Like

I actually prefer that this is explicit in Go (compared to say Ruby, which returns the last value automatically), it doesn’t take much effort to type out return x,y and it makes the intent far clearer.

I agree for one or two return’s in a function, note that it’s completely optional. But when you have many return’s for example and you can’t do the check(err) trick because you want to return err the code gets cluttered.

The check(err) thing is not generally the right thing to do so I don’t think it’s something we should try to spread further, as a pattern. But I also don’t think

f, err := os.Open("/tmp/dat")
if err != nil {
  return err

is cluttered - after seeing it about a hundred million times it’s highly recognizable even at a distance.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.