Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Go Dictionary
  3. Comments (// and /* */)

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

TypeSyntaxDescription
Single-line comment// textEverything 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 nameA // 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.

ConventionDescription
Start with the declaration nameBeginning with "ExampleFunc ..." makes the comment easy to find in go doc listings and grep output.
First sentence is the summarygodoc displays the first sentence on index pages. Write the first sentence so it is meaningful on its own.
Begin package comments with // Package nameThe convention is to open with "// Package math ..." for package-level comments.
No blank line between comment and declarationA blank line between the comment and the declaration prevents it from being recognized as a doc comment.
Example functionsFunctions 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

DecisionSituationReason
Write a commentThe reason why something was implemented a certain wayDesign decisions and trade-offs that cannot be understood from the code alone help your future self and other developers.
Write a commentComplex algorithms or formulasAdd a brief description of what a piece of logic does when its behavior is not immediately obvious at a glance.
Write a commentExported (capitalized) identifiersIn Go, it is conventional to document all exported identifiers with a doc comment. go doc reads these comments.
Write a commentImmediately before the package declarationA package comment describing the package's purpose and usage is expected. It serves as the entry point for go doc output.
No comment neededLogic that is obvious from reading the codeSelf-evident explanations become noise. Clear variable and function names remove the need for such comments.
No comment neededChange history or deleted codeBecause 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 .