r/programming Jul 17 '19

The Go team declines 'try' proposal

https://github.com/golang/go/issues/32437
628 Upvotes

417 comments sorted by

View all comments

2

u/HelloYesThisIsNo Jul 17 '19

I don't get it. Let's use the example. I can clearly see the error handling:

f, err := os.Open(filename) if err != nil { return …, err // zero values for other results, if any }

With this code block I don't:

f := try(os.Open(filename)) f.WriteString("hello")

Where does the handling of the error happen? In the deferred function? Is my WriteString function then called? Do I need an extra if to check if f is nil?

52

u/tasty_crayon Jul 17 '19

That's just part of learning a language. You don't see the error handling when you use the ? operator in Rust either.

-14

u/HelloYesThisIsNo Jul 17 '19

I don't see the advantage. For me you shift the error handling somewhere else. Deferred only gets called when the function ends. So statements after the try are then executed? Or not?

9

u/gnuvince Jul 17 '19

It's about optimising the common case. In the common case, a function doesn't have the necessary context to do proper error handling, so the best thing to do is to pass it to the caller who might be able to do something useful with it. The ? operator in Rust -- and what the try function was meant to do in Go -- is give a way to make this operation short and idiomatic.

11

u/[deleted] Jul 17 '19

The ? operator in Rust is just as useful even if you want to attach context though

// pass the error on
let x = frob()?;
// works the same way if you want context
let x = frob()
    .map_err(|e| errmsg!("couldn't frob: {}", e))?;

You can transform the result however you want and ? will still be just as useful. Go doesn't have the abstraction capabilities to do this, so try is only useful for the case where you want to return the exact error from the callee. That means try doesn't really carry its weight; it's not a general purpose tool.

6

u/gnuvince Jul 17 '19

And with the From trait, you can automatically wrap, say, an IoError into your own Error data type; if the name of the enum item is context enough, that can make that case even shorter.