In Go, “} else {” must all be one line

Learning Go.

The following code:

		if elm, ok := retval[w]; ok {
			retval[w] = elm + 1
		} 
		else {
			retval[w] = 1
		}

Results in the following compiler error:

.\main.go:16:3: syntax error: unexpected else, expected }
.\main.go:19:2: syntax error: non-declaration statement outside function body

But the following “} else {” on one line fixes it:

		if elm, ok := retval[w]; ok {
			retval[w] = elm + 1
		} else {
			retval[w] = 1
		}

Because https://go.dev/ref/spec#Semicolons. (Go inserts a semicolon at the end of a line if the line ends with “}”.)

Short break for head exploding.

Ok, I guess. You’d think the tutorial would mention it, though. (Oh, look! A complaint icon, right on the page! https://github.com/golang/tour/issues/1481)

1 thought on “In Go, “} else {” must all be one line

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.