From 625960b11fa6fd9fe3fcda1d1c25339f31749082 Mon Sep 17 00:00:00 2001 From: Daniel Frederick Crisman Date: Sun, 19 Mar 2023 23:38:22 -0400 Subject: [PATCH] tour: handle error rather than print both In "tour/methods/20" ("Exercise: Errors") just after the slide explaining "calling code should handle errors by testing whether the error equals nil" the example code in the errors exercise provides a main that calls functions expecting error values and does not check them. Checking error values is the expected go way of doing things and should be shown. In the successful case it is also odd to show the "nil" of no error when printing the correct answer (see golang/tour#273). Printing the likely undefined float64 root value when there is an error is also confusing. Update "methods/exercise-errors.go" and matched solution to only print error on error and only root otherwise. Fixes golang/tour#273 Fixes golang/tour#230 --- _content/tour/methods/exercise-errors.go | 9 +++++++-- _content/tour/solutions/errors.go | 9 +++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/_content/tour/methods/exercise-errors.go b/_content/tour/methods/exercise-errors.go index 22e933b2f4..b516f6d49e 100644 --- a/_content/tour/methods/exercise-errors.go +++ b/_content/tour/methods/exercise-errors.go @@ -11,6 +11,11 @@ func Sqrt(x float64) (float64, error) { } func main() { - fmt.Println(Sqrt(2)) - fmt.Println(Sqrt(-2)) + for _, number := range []float64{2, -2} { + if root, err := Sqrt(number); err == nil { + fmt.Println(root) + } else { + fmt.Println(err) + } + } } diff --git a/_content/tour/solutions/errors.go b/_content/tour/solutions/errors.go index e8de49e5e6..bfa5b87fbc 100644 --- a/_content/tour/solutions/errors.go +++ b/_content/tour/solutions/errors.go @@ -35,6 +35,11 @@ func Sqrt(f float64) (float64, error) { } func main() { - fmt.Println(Sqrt(2)) - fmt.Println(Sqrt(-2)) + for _, number := range []float64{2, -2} { + if root, err := Sqrt(number); err == nil { + fmt.Println(root) + } else { + fmt.Println(err) + } + } }