https://play.golang.org/p/d_fQWzXnlAm
If you are going to use panic, then choose a place where you can recover gracefully and report the error. I do agree, that it is an mistake to return an error code if your assignment was to write a function that only has valid input. The software engineer giving you the assignment may be doing data validation else where and is wrapping a higher level function with a defer to deal with errors. If you are working on a team, it is best to produce what is expected, not something better. On Fri, May 18, 2018 at 7:33 PM <[email protected]> wrote: > I may have misunderstood the question. I follow the idea of panic when the > program is in an invalid state. > > If Divide can receive any input then this is probably a better API: > > func Divide(a, b float64) (float64, error) { > > where you would return an ErrDivideByZero made with errors.New as a global > exported var instead of panicking. > > But if Divide can only receive valid input then that assert seems > appropriate to me. > > Matt > > On Monday, May 14, 2018 at 7:38:32 PM UTC-5, Tristan Muntsinger wrote: >> >> Is it reasonable to use a function like "Assert" below to do validation >> checking in Go? If not, why not? >> >> func Assert(t bool, msg string) { >> if !t { >> debug.SetTraceback("all") >> debug.PrintStack() >> log.Fatal("Assertion failed: " + msg) >> } >> } >> >> func Divide(a float64, b float64) float64 { >> Assert(b != 0, "divide by 0") >> return a / b >> } >> >> func main() { >> fmt.Println(Divide(10, 5)) >> } >> >> Thanks, >> -Tristan >> >> -- > You received this message because you are subscribed to a topic in the > Google Groups "golang-nuts" group. > To unsubscribe from this topic, visit > https://groups.google.com/d/topic/golang-nuts/viuz4JTVelE/unsubscribe. > To unsubscribe from this group and all its topics, send an email to > [email protected]. > For more options, visit https://groups.google.com/d/optout. > -- 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.
