Use // for single-line comments and /* ... */ for multi-line blocks, but prefer // even for multiple lines because it integrates better with Go's documentation tools like godoc. Go does not support // for multi-line comments in the same way some other languages do; you must repeat // for each line or use the C-style block syntax.
For single-line comments, place // at the start of the line or after code. For multi-line comments, wrap the text in /* and */. However, the Go community generally discourages /* ... */ for regular comments because godoc only extracts documentation from // comments that immediately precede a top-level declaration. Use /* ... */ sparingly, primarily for disabling large blocks of code during debugging or for license headers at the very top of a file.
Here is a practical example showing the standard usage:
package main
import "fmt"
// Single-line comment explaining the function.
// This is the preferred style for documentation.
// godoc will pick this up automatically.
func Add(a, b int) int {
// Inline comment for a specific operation
sum := a + b // Another inline comment
return sum
}
/*
Multi-line comment block.
While valid, this is rarely used for documentation
because godoc ignores it unless it's a license header.
*/
func Multiply(a, b int) int {
return a * b
}
func main() {
fmt.Println(Add(2, 3))
}
If you need to write documentation that appears in godoc or IDE tooltips, always use // and place it directly before the declaration with no blank lines in between. For example:
// Calculate returns the sum of two integers.
// It handles overflow by returning the maximum int value.
func Calculate(x, y int) int {
// Implementation details here
return x + y
}
Avoid using /* ... */ for function descriptions or variable explanations, as this text will not appear in generated documentation. Stick to // for everything except license headers or temporary code disabling. This ensures your code remains consistent with Go's tooling ecosystem and community standards.