* Marvin Renich <m...@renich.org> [170621 09:48]:
> package main
> 
> import (
>       "fmt"
> )
> 
> func Calc(a int) (r int, err error) {
>       if a == 0 {
>               err = fmt.Errorf("Bad argument")
>               return
>       }
>       r = 72 / a
>       return
> }
> 
> func main() {
>       fmt.Println(Calc(3))
>       fmt.Println(Calc(0))
> }

I have to add, however, that stylistically, I usually prefer to use
explicit return values, like this:

func Calc(a int) (r int, err error) {
        if a == 0 {
                return 0, fmt.Errorf("Bad argument")
        }
        r = 72 / a // I am assuming that calculating r is much more complex
        return r, nil
}

This makes my intention clear about when a return value is a "default"
and when it is the result of a calculation.  It also avoids accidentally
returning a non-nil err when I keep re-using err throughout a function
to hold the error returns from function calls made from within my
function.

...Marvin

-- 
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 golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to