Prefix unexported top-level var
s and const
s with _
to make it clear when
they are used that they are global symbols.
Rationale: Top-level variables and constants have a package scope. Using a generic name makes it easy to accidentally use the wrong value in a different file.
Bad | Good |
---|---|
// foo.go
const (
defaultPort = 8080
defaultUser = "user"
)
// bar.go
func Bar() {
defaultPort := 9090
...
fmt.Println("Default port", defaultPort)
// We will not see a compile error if the first line of
// Bar() is deleted.
} |
// foo.go
const (
_defaultPort = 8080
_defaultUser = "user"
) |
Exception: Unexported error values may use the prefix err
without the underscore.
See Error Naming.