Go Comments
Comments let you annotate Go code with notes that the compiler ignores, using either single-line or multi-line syntax.
Single-Line Comments
A single-line comment starts with two forward slashes, //. Everything from // to the end of that line is ignored by the compiler.
Single-Line Comment Example
package main
import "fmt"
func main() {
// This line prints a greeting
fmt.Println("Hello!") // this runs the actual code
}Multi-Line Comments
A multi-line, or block, comment starts with /* and ends with */. Everything between those markers is ignored, even across several lines.
Multi-Line Comment Example
package main
import "fmt"
/*
This program demonstrates
a simple block comment
spanning multiple lines.
*/
func main() {
fmt.Println("Comments don't affect output")
}- Explain why code does something, not just what it does
- Temporarily disable a line of code while debugging
- Document a function's purpose right above its declaration
- Leave TODO notes for work that still needs finishing
Doc Comments
A comment placed directly above a function, type, or variable declaration, with no blank line in between, becomes that declaration's documentation. Tools like godoc read these comments to generate reference pages automatically.
Documenting a Function
package main
import "fmt"
// greet prints a friendly welcome message to the console.
func greet() {
fmt.Println("Welcome to Go!")
}
func main() {
greet()
}Note: By convention, doc comments start with the name of the thing they describe, as in 'greet prints a friendly...' — this reads naturally in generated documentation.
Note: Block comments cannot be nested — putting a /* ... */ comment inside another /* ... */ comment will end the outer comment early and likely cause a compile error.
Exercise: Go Comments
Which syntax starts a single-line comment in Go?