Comments & gofmt
Prerequisites: Methods
Syntax
// A single-line comment.
/*
A block comment — mostly used for temporarily disabling code
or for long package documentation.
*/
Doc comments
A comment placed directly above a package, function, type,
constant, or variable (with no blank line in between) is its
doc comment. Tools like go doc, pkg.go.dev, and your
editor's hover tooltips display it. By convention it's a full
sentence that starts with the name being documented:
// Package geometry provides simple shape calculations.
package geometry
// Rectangle is an axis-aligned rectangle.
type Rectangle struct {
Width, Height float64
}
// Area returns the rectangle's area.
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
gofmt: one standard layout
Go has a single official code format, applied by the gofmt tool.
It uses tabs for indentation, aligns related comments and
struct fields, and settles brace placement — so style debates
simply don't happen in Go code reviews.
gofmt -l . # list files that aren't formatted
gofmt -w main.go # rewrite a file in place
go fmt ./... # format every package in the module
Most editors run it on save once the Go extension is installed.
go vet: catching suspicious code
go vet looks for code that compiles but is probably wrong —
such as a Printf verb that doesn't match its argument:
go vet ./...
./main.go:8:5: fmt.Printf format %d has arg name of wrong type string
(go test runs a subset of these checks automatically.)
Common mistakes
- Starting a doc comment with "This function..." instead of the
function's name — tools and readers expect
// Name .... - Leaving a blank line between the comment and the declaration, which stops it being treated as a doc comment.
- Hand-formatting code or arguing about indentation — let
gofmtdecide. - Commenting what obvious code does (
i++ // add one to i) instead of why it does it.
Practice
Add doc comments to this function and constant, following the Go convention:
const maxRetries = 3
func celsiusToFahrenheit(c float64) float64 {
return c*9/5 + 32
}
Show solution
// maxRetries is how many times a failed request is retried.
const maxRetries = 3
// celsiusToFahrenheit converts a temperature from degrees
// Celsius to degrees Fahrenheit.
func celsiusToFahrenheit(c float64) float64 {
return c*9/5 + 32
}