Go comments and automatic semicolon insertion
Comments describe intent
A line comment begins with // and ends at the line break. A block comment begins with /* and ends at the first */; block comments do not nest. Ordinary comments do not execute. Explain why code exists rather than repeating what the statement already says.
package main
import "fmt"
func main() { // Use a small sample count for the demo. fmt.Println(3)
/* The next message marks the end. */ fmt.Println("Ready")}The output is 3 followed by Ready. The comments add no output. A block comment without a newline acts like a space; a comment containing a newline or a line comment acts like a newline. Some special comments are tool directives, which we will cover later.
Where line breaks matter
Go inserts semicolons automatically after certain final tokens on a line, including identifiers, literals, ), ], }, ++, --, and the keywords break, continue, fallthrough, return. A semicolon can also be omitted before a closing ) or }. Keep the opening brace of func main() on the same line as the closing parenthesis. Break a long addition after +, not before it.
package main
import "fmt"
func main() { fmt.Println(2 + 3)}The output is 5. The plus sign does not trigger semicolon insertion, so the expression continues. Moving + to the next line after 2 would cause a syntax error here. Use gofmt to normalize valid source; it cannot always repair invalid line breaks.
Try it locally
Print the sum 8 + 4 split across two lines after the plus sign. Add a line comment explaining that the values are sample quantities. Expected: 12.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tokens and Declarations 02: Go comments and automatic semicolon insertion
Check the lesson objective before moving on.
What terminates an ordinary line comment?
Where should the opening brace of func main() appear?