Skip to content

Commit c13e7cf

Browse files
committed
_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
1 parent cd3dc42 commit c13e7cf

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

_content/tour/flowcontrol.article

+14
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,20 @@ of the `else` blocks.
6969
(Both calls to `pow` return their results before the call to `fmt.Println`
7070
in `main` begins.)
7171

72+
Because of the way Go parses source code you must put the `else` on the same line
73+
as the closing brace of the associated `if` block.
74+
`else` after a newline generates a syntax error:
75+
76+
if v := math.Pow(x, n); v < lim {
77+
return v
78+
}
79+
else { // syntax error: unexpected else, expecting }
80+
fmt.Printf("%g >= %g\n", v, lim)
81+
}
82+
83+
If you are interested in details on why this is, read the Language Specification sections
84+
on [[/ref/spec#Semicolons][Semicolons]] and [[/ref/spec#If_statements][If Statements]].
85+
7286
.play flowcontrol/if-and-else.go
7387

7488
* Exercise: Loops and Functions

0 commit comments

Comments
 (0)