From: Rob Pike
+Go is a new language. Although it's in the C family of languages
+it has some unusual properties that make effective Go programs
+different in character from programs in C, C++, or Java.
+To write Go well, it's important to understand its properties
+and idioms.
+
This document gives tips for writing clear, idiomatic Go code
and points out common mistakes.
@@ -287,11 +295,11 @@ A comment can introduce a group of related constants or variables.
Introduction
+
-// Flags to Open wrapping those of the underlying system.
+// Flags to Open, wrapping those of the underlying system.
// Not all flags may be implemented on a given system.
const (
- O_RDONLY = syscall.O_RDONLY; // open the file read-only.
- O_WRONLY = syscall.O_WRONLY; // open the file write-only.
+ O_RDONLY = syscall.O_RDONLY; // Open file read-only.
+ O_WRONLY = syscall.O_WRONLY; // Open file write-only.
...
)
@@ -303,9 +311,9 @@ a mutex.
-// Variables protected by counterLock. +// Variables protected by countLock. var ( - counterLock sync.Mutex; + countLock sync.Mutex; inputCount uint32; outputCount uint32; errorCount uint32; @@ -357,9 +365,8 @@ the bufferedReader
isbufio.Reader
, notbufio.B Similarly,
once.Do
is as precise and evocative asonce.DoOrWaitUntilDone
, andonce.Do(f)
reads better thanonce.DoOrWaitUntilDone(f)
. -Contrary to popular belief, encoding small essays into -function names does not make it possible -to use them without documentation. +Encoding small essays into function names is not Go style; +clear names with good documentation is.Use the -er convention for interface names
@@ -564,24 +571,41 @@ codeUsing(f);Return structured errors
-Implementations ofos.Error
s should -describe the error but also include context. +Implementations ofos.Error
should +describe the error and provide context. For example,os.Open
returns anos.PathError
: /src/pkg/os/file.go:-XXX definition of PathError and .String +// PathError records an error and the operation and +// file path that caused it. +type PathError struct { + Op string; + Path string; + Error Error; +} + +func (e *PathError) String() string { + return e.Op + " " + e.Path + ": " + e.Error.String(); +}PathError
'sString
formats -the error nicely and is the usual way the error gets used. -Callers that care about the precise error details can -use a type switch or a type guard to look for specific -errors and then extract details. - +the error nicely, including the operation and file name +tha failed; just printing the error generates a +message, such as-XXX example here - MkdirAll +open /etc/passwx: no such file or directory+that is useful even if printed far from the call that +triggered it. + + ++Callers that care about the precise error details can +use a type switch or a type guard to look for specific +errors and extract details. +
Programmer-defined types