From c13e7cf91223cdd80d1fd39073ddf90c94322531 Mon Sep 17 00:00:00 2001 From: Daniel Frederick Crisman Date: Fri, 12 May 2023 22:44:55 -0400 Subject: [PATCH] _content/tour: document no newline before else Many users of the Go Tour trip over using else after a newline which generates a syntax error that is hard to understand unless the reader is primed to think about a newline before the else. "tour/flowcontrol/7" ("If and else") the slide that first talks about else seems the right place to update. Add statement about required location of else after if block, provide an invalid else code example mirroring the slide's program, and provide links to the language spec for details. Fixes golang/tour#1481 Fixes golang/tour#1427 Fixes golang/tour#1062 Fixes golang/tour#442 --- _content/tour/flowcontrol.article | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/_content/tour/flowcontrol.article b/_content/tour/flowcontrol.article index 448cb76765..2c64e0a72a 100644 --- a/_content/tour/flowcontrol.article +++ b/_content/tour/flowcontrol.article @@ -69,6 +69,20 @@ of the `else` blocks. (Both calls to `pow` return their results before the call to `fmt.Println` in `main` begins.) +Because of the way Go parses source code you must put the `else` on the same line +as the closing brace of the associated `if` block. +`else` after a newline generates a syntax error: + + if v := math.Pow(x, n); v < lim { + return v + } + else { // syntax error: unexpected else, expecting } + fmt.Printf("%g >= %g\n", v, lim) + } + +If you are interested in details on why this is, read the Language Specification sections +on [[/ref/spec#Semicolons][Semicolons]] and [[/ref/spec#If_statements][If Statements]]. + .play flowcontrol/if-and-else.go * Exercise: Loops and Functions