Hi!
On Sat, Feb 24, 2018 at 02:02:37PM -0800, Bakul Shah wrote:
> r := os.Open(filename)
> if isError(r) { return r.(error) }
> f := r.(*os.File) // or better: var f *os.File; f = r
>
> 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.
>
> 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
Actually you can have such a sum type right now, without any changes to
syntax or stdlib, and with much more pleasant usage syntax.
Full example: https://play.golang.org/p/tVSAqRprmKI
Short version to just get a taste:
type Time struct {
Err error
*time.Time
}
func now(pass bool) Time {
if !pass {
return Time{Err: errors.New("not now")}
}
now := time.Now()
return Time{Time: &now}
}
t := now(…)
f t.Err != nil {
return t.Err
}
// Use t just like time.Time.
--
WBR, Alex.
--
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.