On 24 February 2018 at 22:02, Bakul Shah <[email protected]> wrote:
> r := os.Open(filename)
> if isError(r) { return r.(error) }
> f := r.(*os.File) // or better: var f *os.File; f = r
I don't think the "or better" alternative would be possible. The of r
is still `*os.File|error`, not *os.File, and this not assignable to a
*os.File without some kind of type assertion. Unless somehow isError
is a special language builtin that manages to change the type of r
after calling it. I can't see how that would work though.
So here we've got two type assertions, both of which can potentially
panic. At least, I always look very carefully at type assertions
without a `, ok` clause because the consequences are so bad if you get
them wrong.
> Error checking being a common pattern, isError() can be added as a builtin
> or trivially in errors pkg. Likely the enclosing function also returns an
> error
> so the return in the second line above can be just return r but with the
> current product type approach you’d have return nil, err.
That's only the case if you're returning exactly the same type.
> You are only looking at code after returning. Code within a function benefits
> more (gets simplified).
>
> func f(s string) (int|error) { // instead of (int,error)
> ...
> return err // instead of return 0,err
> ...
> return 1 // instead of return 1,nil
> // and return n, err case disappears
>
> Having to return an extra thing that gets discarded right away is annoying.
It's perhaps a little annoying (although it would be less annoying if
we had a standard identifier for "zero value - see
https://github.com/golang/go/issues/19642), but AFAICS using sum types
instead would end up more annoying in practice. Also, it's not *that*
uncommon to need to return both a valid value and an error.
cheers,
rog.
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.