Go Comments
Comments are notes for humans. The compiler skips them completely. Use them to explain why code does something, to document functions for other developers, or to switch off a line temporarily while you experiment.
Single-line comments
A single-line comment starts with // and runs to the end of the line. It can sit on its own line or after code.
package main
import "fmt"
func main() {
// Print a greeting
fmt.Println("Hi there!") // this comment is after the code
// fmt.Println("This line is switched off")
}Hi there!
Multi-line comments
A block comment starts with /* and ends with */. Everything in between is ignored, even across several lines.
package main
import "fmt"
func main() {
/*
The next statement prints the
number of days in a week.
*/
fmt.Println(7)
fmt.Println(/* inline note */ "block comments can sit inside a line")
}7
block comments can sit inside a line
Block comments cannot be nested: the first */ always ends the comment. In practice, Go programmers use // for almost everything and keep /* */ for disabling larger chunks of code.
Doc comments
A comment placed directly above a package, function, type, constant or variable, with no blank line in between, is a doc comment. Tools such as go doc, editors and the pkg.go.dev website show it as documentation. By convention it starts with the name it describes and is a full sentence.
package main
import "fmt"
// Area returns the area of a rectangle with the given width and height.
func Area(width, height float64) float64 {
return width * height
}
// DefaultSize is the side length used when none is given.
const DefaultSize = 4.0
func main() {
fmt.Println(Area(DefaultSize, 2.5))
}10
Running go doc Area in that package would print the comment above the function.
| Comment style | Typical use |
|---|---|
// text |
Explanations, doc comments, temporarily disabling a line |
/* text */ |
Disabling a block of code, package docs in a separate doc.go file |
//go:build linux |
A directive — not a comment for humans but an instruction to the toolchain |
Note: Lines like
//go:buildor//go:embedlook like comments but are directives. They must start with//go:with no space after the slashes.
Good commenting habits
- Explain why, not what.
i++ // increase iadds nothing;i++ // skip the header rowdoes. - Write doc comments for everything you export —
go vetstyle checkers will remind you. - Delete commented-out code before committing. Version control remembers it for you.
Test yourself
Which syntax starts a single-line comment in Go?
#--//<!--
What makes a comment a *doc comment*?
- It starts with
/// - It is placed directly above a declaration with no blank line
- It is written in upper case
- It uses
/** */