Skip to content

Commit

Permalink
_content/tour: document no newline before else
Browse files Browse the repository at this point in the history
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
  • Loading branch information
crisman committed May 13, 2023
1 parent cd3dc42 commit c13e7cf
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions _content/tour/flowcontrol.article
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit c13e7cf

Please sign in to comment.