Comments (// and /* */)
Go has two types of comments: single-line comments (//) and block comments (/* */). Documentation comments in Go do not require special tags — a // comment written immediately before a declaration is treated as its documentation. The standard tools go doc and godoc parse these comments to generate documentation. By convention, the first sentence of a comment serves as a summary.
Syntax
var x int = 10 // Inline comment — can also be written after code.
/*
Block comment — everything between /* and */ is a comment.
Used for multi-line comments or for commenting out blocks of code.
*/
// ExampleFunc documents the function that immediately follows this comment.
// In Go, // is the conventional style for doc comments, not /* */.
// The convention is to start the comment with the declaration name ("ExampleFunc ...").
func ExampleFunc() {}
// Package math provides math utilities.
// Package comments are written immediately before the package declaration.
package math
Comment Types
| Type | Syntax | Description |
|---|---|---|
| Single-line comment | // text | Everything from // to the end of the line becomes a comment. The most commonly used comment type, including for doc comments. |
| Block comment | /* text */ | Used for multi-line explanations or temporary commenting out. Not used for documentation comments in idiomatic Go. |
| Documentation comment | // starting with the declaration name | A // comment written immediately before a declaration becomes its documentation. Parsed by go doc and godoc. |
| Package comment | // Package name ... | Written immediately before the package declaration. The convention is to start with // Package name. Describes the overall purpose of the package. |
Documentation Comment Conventions
Go documentation comments have no special tags — the quality of the documentation depends on following naming and phrasing conventions. The standard library provides a useful reference for style.
| Convention | Description |
|---|---|
| Start with the declaration name | Beginning with "ExampleFunc ..." makes the comment easy to find in go doc listings and grep output. |
| First sentence is the summary | godoc displays the first sentence on index pages. Write the first sentence so it is meaningful on its own. |
| Begin package comments with // Package name | The convention is to open with "// Package math ..." for package-level comments. |
| No blank line between comment and declaration | A blank line between the comment and the declaration prevents it from being recognized as a doc comment. |
| Example functions | Functions whose names start with Example (e.g., func ExampleFoo()) are executed as doc tests by go test. |
Use the go doc command to display documentation for packages, types, and functions.
go doc fmt go doc fmt.Println go doc -all math
When to Write Comments and When Not To
| Decision | Situation | Reason |
|---|---|---|
| Write a comment | The reason why something was implemented a certain way | Design decisions and trade-offs that cannot be understood from the code alone help your future self and other developers. |
| Write a comment | Complex algorithms or formulas | Add a brief description of what a piece of logic does when its behavior is not immediately obvious at a glance. |
| Write a comment | Exported (capitalized) identifiers | In Go, it is conventional to document all exported identifiers with a doc comment. go doc reads these comments. |
| Write a comment | Immediately before the package declaration | A package comment describing the package's purpose and usage is expected. It serves as the entry point for go doc output. |
| No comment needed | Logic that is obvious from reading the code | Self-evident explanations become noise. Clear variable and function names remove the need for such comments. |
| No comment needed | Change history or deleted code | Because version control (git) is available, there is no need to keep old code or change dates in comments. |
Sample Code
comment_basic.go
// comment_basic.go — Basic usage of Go comment syntax.
package main
import "fmt"
/*
Define the number of items as a constant.
Block comments are occasionally used for file-level explanations
or to comment out large blocks of code.
*/
const itemCount = 3
func main() {
// Define arrays of item names and prices
items := [itemCount]string{"widget", "gadget", "device"}
prices := [itemCount]int{1200, 3500, 800} // Prices before tax
total := 0
for i := 0; i < itemCount; i++ {
fmt.Printf("%-10s %5d yen\n", items[i], prices[i])
total += prices[i]
}
fmt.Println("----------")
fmt.Printf("%-10s %5d yen\n", "Total", total)
}
The same logic can also be written as:
go run comment_basic.go
widget 1200 yen gadget 3500 yen device 800 yen ---------- Total 5500 yen
calculator.go
//
// A // comment written immediately before an exported declaration
// becomes its documentation, readable via the go doc command.
package main
import (
"errors"
"fmt"
)
// Sum computes the sum of an integer slice and returns it.
//
func Sum(values []int) (int, error) {
if values == nil {
return 0, errors.New("values must not be nil")
}
total := 0
for _, v := range values {
total += v
}
return total, nil
}
// Average computes the average of an integer slice and returns it.
//
// Returns 0.0 and an error if the slice is empty.
func Average(values []int) (float64, error) {
if len(values) == 0 {
/* Early return to prevent division by zero */
return 0.0, errors.New("values must not be empty")
}
sum, err := Sum(values)
if err != nil {
return 0.0, err
}
// Cast to float64 to avoid integer division
return float64(sum) / float64(len(values)), nil
}
func main() {
scores := []int{85, 92, 78, 95, 60}
sum, _ := Sum(scores)
fmt.Println("Sum: ", sum)
avg, _ := Average(scores)
fmt.Printf("Average: %.1f\n", avg)
// Empty slice case
_, err := Average([]int{})
fmt.Println("Empty: ", err)
}
The same logic can also be written as:
go run calculator.go
Sum: 410 Average: 82.0 Empty: values must not be empty
Overview
Go has two comment types, // and /* */, but documentation comments use plain //. A // comment written immediately before a declaration — with no blank line in between — is treated as its documentation by go doc and godoc. No special tags are required.
The convention is to add a doc comment to every exported identifier (those starting with a capital letter), and to begin each comment with the declaration name ("Sum computes ..."). Package comments follow the form "// Package name ..." and are placed immediately before the package declaration. The first sentence of a comment is used as a summary, so it should be meaningful on its own.
If you find any errors or copyright issues, please contact us.