Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 1 | # Go Code Review Comments |
| 2 | |
| 3 | This page collects common comments made during reviews of Go code, so |
| 4 | that a single detailed explanation can be referred to by shorthands. |
| 5 | This is a laundry list of common mistakes, not a style guide. |
| 6 | |
Dmitri Shuralyov | 2c403c2 | 2016-09-25 00:07:16 -0700 | [diff] [blame] | 7 | You can view this as a supplement to https://golang.org/doc/effective_go.html. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 8 | |
| 9 | **Please discuss changes before editing this page**, even _minor_ ones. Many people have opinions and this is not the place for edit wars. |
| 10 | |
Andrew Gerrand | e6f8213 | 2016-02-09 08:26:28 +1100 | [diff] [blame] | 11 | * [gofmt](#gofmt) |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 12 | * [Comment Sentences](#comment-sentences) |
Jaana B. Dogan | b824d41 | 2017-01-30 09:25:17 -0800 | [diff] [blame] | 13 | * [Contexts](#contexts) |
Jaana B. Dogan | dcc731c | 2017-01-30 09:28:00 -0800 | [diff] [blame] | 14 | * [Copying](#copying) |
Jaana B. Dogan | f11f8f7 | 2017-01-30 10:05:50 -0800 | [diff] [blame] | 15 | * [Crypto Rand](#cryptorand) |
Earl J. Wagner | 7dda73c | 2015-01-05 11:43:49 -0600 | [diff] [blame] | 16 | * [Declaring Empty Slices](#declaring-empty-slices) |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 17 | * [Doc Comments](#doc-comments) |
| 18 | * [Don't Panic](#dont-panic) |
| 19 | * [Error Strings](#error-strings) |
Jaana B. Dogan | b181e78 | 2017-01-30 09:36:22 -0800 | [diff] [blame] | 20 | * [Examples](#examples) |
Jaana B. Dogan | 8590e71 | 2017-01-30 09:38:59 -0800 | [diff] [blame] | 21 | * [Goroutine Lifetimes](#goroutine-lifetimes) |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 22 | * [Handle Errors](#handle-errors) |
| 23 | * [Imports](#imports) |
| 24 | * [Import Dot](#import-dot) |
Jaana B. Dogan | ad8c445 | 2017-01-30 10:15:18 -0800 | [diff] [blame^] | 25 | * [In-Band Errors](#in-band-errors) |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 26 | * [Indent Error Flow](#indent-error-flow) |
| 27 | * [Initialisms](#initialisms) |
| 28 | * [Line Length](#line-length) |
| 29 | * [Mixed Caps](#mixed-caps) |
| 30 | * [Named Result Parameters](#named-result-parameters) |
| 31 | * [Naked Returns](#naked-returns) |
| 32 | * [Package Comments](#package-comments) |
| 33 | * [Package Names](#package-names) |
| 34 | * [Pass Values](#pass-values) |
| 35 | * [Receiver Names](#receiver-names) |
| 36 | * [Receiver Type](#receiver-type) |
| 37 | * [Useful Test Failures](#useful-test-failures) |
| 38 | * [Variable Names](#variable-names) |
| 39 | |
Andrew Gerrand | e6f8213 | 2016-02-09 08:26:28 +1100 | [diff] [blame] | 40 | ## gofmt |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 41 | |
Dmitri Shuralyov | 2c403c2 | 2016-09-25 00:07:16 -0700 | [diff] [blame] | 42 | Run [gofmt](https://golang.org/cmd/gofmt/) on your code to automatically fix the majority of mechanical style issues. Almost all Go code in the wild uses `gofmt`. The rest of this document addresses non-mechanical style points. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 43 | |
Andrew Gerrand | 2c6abb8 | 2016-02-09 08:25:13 +1100 | [diff] [blame] | 44 | An alternative is to use [goimports](https://godoc.org/golang.org/x/tools/cmd/goimports), a superset of `gofmt` which additionally adds (and removes) import lines as necessary. |
| 45 | |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 46 | ## Comment Sentences |
| 47 | |
Dmitri Shuralyov | 2c403c2 | 2016-09-25 00:07:16 -0700 | [diff] [blame] | 48 | See https://golang.org/doc/effective_go.html#commentary. Comments documenting declarations should be full sentences, even if that seems a little redundant. This approach makes them format well when extracted into godoc documentation. Comments should begin with the name of the thing being described and end in a period: |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 49 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 50 | ```go |
Martin Bertschler | 6db1649 | 2016-10-23 23:00:46 +0200 | [diff] [blame] | 51 | // Request represents a request to run a command. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 52 | type Request struct { ... |
| 53 | |
| 54 | // Encode writes the JSON encoding of req to w. |
| 55 | func Encode(w io.Writer, req *Request) { ... |
| 56 | ``` |
| 57 | |
| 58 | and so on. |
| 59 | |
Jaana B. Dogan | b824d41 | 2017-01-30 09:25:17 -0800 | [diff] [blame] | 60 | ## Contexts |
| 61 | |
| 62 | Values of the context.Context type carry security credentials, |
| 63 | tracing information, deadlines, and cancellation signals across API |
| 64 | and process boundaries. Go programs pass Contexts explicitly along |
| 65 | the entire function call chain from incoming RPCs and HTTP requests |
| 66 | to outgoing requests. |
| 67 | |
| 68 | Most functions that use a Context should accept it as their first parameter: |
| 69 | |
| 70 | ``` |
| 71 | func F(ctx context.Context, /* other arguments */) {} |
| 72 | ``` |
| 73 | |
| 74 | A function that is never request-specific may use context.Background(), |
| 75 | but err on the side of passing a Context even if you think you don't need |
| 76 | to. The default case is to pass a Context; only use context.Background() |
| 77 | directly if you have a good reason why the alternative is a mistake. |
| 78 | |
| 79 | Don't add a Context member to a struct type; instead add a ctx parameter |
| 80 | to each method on that type that needs to pass it along. The one exception |
| 81 | is for methods whose signature must match an interface in the standard library |
| 82 | or in a third party library. |
| 83 | |
| 84 | Don't create custom Context types or use interfaces other than Context in |
| 85 | function signatures. |
| 86 | |
| 87 | If you have application data to pass around, put it in a parameter, |
| 88 | in the receiver, in globals, or, if it truly belongs there, in a Context value. |
| 89 | |
| 90 | Contexts are immutable, so it's fine to pass the same ctx to multiple |
| 91 | calls that share the same deadline, cancellation signal, credentials, |
| 92 | parent trace, etc. |
| 93 | |
Jaana B. Dogan | dcc731c | 2017-01-30 09:28:00 -0800 | [diff] [blame] | 94 | ## Copying |
| 95 | |
| 96 | To avoid unexpected aliasing, be careful when copying a struct from another package. |
| 97 | For example, the bytes.Buffer type contains a `[]byte` slice and, as an optimization |
| 98 | for small strings, a small byte array to which the slice may refer. If you copy a `Buffer`, |
| 99 | the slice in the copy may alias the array in the original, causing subsequent method |
| 100 | calls to have surprising effects. |
| 101 | |
| 102 | In general, do not copy a value of type `T` if its methods are associated with the |
| 103 | pointer type, `*T`. |
| 104 | |
Earl J. Wagner | 7dda73c | 2015-01-05 11:43:49 -0600 | [diff] [blame] | 105 | ## Declaring Empty Slices |
| 106 | |
Toby Allen | 771f1c7 | 2016-10-14 21:59:05 +0100 | [diff] [blame] | 107 | When declaring a slice, use |
Earl J. Wagner | 7dda73c | 2015-01-05 11:43:49 -0600 | [diff] [blame] | 108 | ```go |
| 109 | var t []string |
| 110 | ``` |
Toby Allen | 771f1c7 | 2016-10-14 21:59:05 +0100 | [diff] [blame] | 111 | rather than |
Earl J. Wagner | 7dda73c | 2015-01-05 11:43:49 -0600 | [diff] [blame] | 112 | ```go |
| 113 | t := []string{} |
| 114 | ``` |
| 115 | |
Earl J. Wagner | e3ee7b0 | 2015-01-11 15:20:33 -0600 | [diff] [blame] | 116 | The former avoids allocating memory if the slice is never appended to. |
Earl J. Wagner | 7dda73c | 2015-01-05 11:43:49 -0600 | [diff] [blame] | 117 | |
Jaana B. Dogan | f11f8f7 | 2017-01-30 10:05:50 -0800 | [diff] [blame] | 118 | ## Crypto Rand |
Jaana B. Dogan | 9b33933 | 2017-01-30 09:32:22 -0800 | [diff] [blame] | 119 | |
| 120 | Do not use package `math/rand` to generate keys, even throwaway ones. |
| 121 | Unseeded, the generator is completely predictable. Seeded with `time.Nanoseconds()`, |
| 122 | there are just a few bits of entropy. Instead, use `crypto/rand`'s Reader, |
| 123 | and if you need text, print to hexadecimal or base64: |
| 124 | |
| 125 | ``` go |
| 126 | import ( |
| 127 | "crypto/rand" |
| 128 | // "encoding/base64" |
| 129 | // "encoding/hex" |
| 130 | "fmt" |
| 131 | ) |
| 132 | |
| 133 | func Key() string { |
| 134 | buf := make([]byte, 16) |
| 135 | _, err := rand.Read(buf) |
| 136 | if err != nil { |
| 137 | panic(err) // out of randomness, should never happen |
| 138 | } |
| 139 | return fmt.Sprintf("%x", buf) |
| 140 | // or hex.EncodeToString(buf) |
| 141 | // or base64.StdEncoding.EncodeToString(buf) |
| 142 | } |
| 143 | ``` |
| 144 | |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 145 | ## Doc Comments |
| 146 | |
Dmitri Shuralyov | 2c403c2 | 2016-09-25 00:07:16 -0700 | [diff] [blame] | 147 | All top-level, exported names should have doc comments, as should non-trivial unexported type or function declarations. See https://golang.org/doc/effective_go.html#commentary for more information about commentary conventions. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 148 | |
| 149 | ## Don't Panic |
| 150 | |
Dmitri Shuralyov | 2c403c2 | 2016-09-25 00:07:16 -0700 | [diff] [blame] | 151 | See https://golang.org/doc/effective_go.html#errors. Don't use panic for normal error handling. Use error and multiple return values. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 152 | |
| 153 | ## Error Strings |
| 154 | |
Steve Carrupt | 6a3e308 | 2016-11-24 09:49:46 +0900 | [diff] [blame] | 155 | Error strings should not be capitalized (unless beginning with proper nouns or acronyms) or end with punctuation, since they are usually printed following other context. That is, use `fmt.Errorf("something bad")` not `fmt.Errorf("Something bad")`, so that `log.Printf("Reading %s: %v", filename, err)` formats without a spurious capital letter mid-message. This does not apply to logging, which is implicitly line-oriented and not combined inside other messages. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 156 | |
Jaana B. Dogan | b181e78 | 2017-01-30 09:36:22 -0800 | [diff] [blame] | 157 | ## Examples |
| 158 | |
| 159 | When adding a new package, include examples of intended usage: a runnable Example, |
| 160 | or a simple test demonstrating a complete call sequence. |
| 161 | |
| 162 | Read more about [testable Example() functions](https://blog.golang.org/examples). |
| 163 | |
Jaana B. Dogan | 8590e71 | 2017-01-30 09:38:59 -0800 | [diff] [blame] | 164 | ## Goroutine Lifetimes |
| 165 | |
| 166 | When you spawn goroutines, make it clear when - or whether - they exit. |
| 167 | |
| 168 | Goroutines can leak by blocking on channel sends or receives: the garbage collector |
| 169 | will not terminate a goroutine even if the channels it is blocked on are unreachable. |
| 170 | |
| 171 | Even when goroutines do not leak, leaving them in-flight when they are no longer |
| 172 | needed can cause other subtle and hard-to-diagnose problems. Sends on closed channels |
| 173 | panic. Modifying still-in-use inputs "after the result isn't needed" can still lead |
| 174 | to data races. And leaving goroutines in-flight for arbitrarily long can lead to |
| 175 | unpredictable memory usage. |
| 176 | |
| 177 | Try to keep concurrent code simple enough that goroutine lifetimes are obvious. |
| 178 | If that just isn't feasible, document when and why the goroutines exit. |
Jaana B. Dogan | b181e78 | 2017-01-30 09:36:22 -0800 | [diff] [blame] | 179 | |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 180 | ## Handle Errors |
| 181 | |
Dmitri Shuralyov | 2c403c2 | 2016-09-25 00:07:16 -0700 | [diff] [blame] | 182 | See https://golang.org/doc/effective_go.html#errors. Do not discard errors using `_` variables. If a function returns an error, check it to make sure the function succeeded. Handle the error, return it, or, in truly exceptional situations, panic. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 183 | |
| 184 | ## Imports |
| 185 | |
Jaana B. Dogan | 860d784 | 2017-01-30 10:08:02 -0800 | [diff] [blame] | 186 | Avoid renaming imports except to avoid a name collision; good package names |
| 187 | should not require renaming. In the event of collision, prefer to rename the most |
| 188 | local or project-specific import. |
| 189 | |
| 190 | |
| 191 | Imports are organized in groups, with blank lines between them. |
| 192 | The standard library packages are always in the first group. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 193 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 194 | ```go |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 195 | package main |
| 196 | |
| 197 | import ( |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 198 | "fmt" |
| 199 | "hash/adler32" |
| 200 | "os" |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 201 | |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 202 | "appengine/foo" |
| 203 | "appengine/user" |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 204 | |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 205 | "code.google.com/p/x/y" |
| 206 | "github.com/foo/bar" |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 207 | ) |
| 208 | ``` |
| 209 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 210 | <a href="https://godoc.org/golang.org/x/tools/cmd/goimports">goimports</a> will do this for you. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 211 | |
| 212 | ## Import Dot |
| 213 | |
| 214 | The import . form can be useful in tests that, due to circular dependencies, cannot be made part of the package being tested: |
| 215 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 216 | ```go |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 217 | package foo_test |
| 218 | |
| 219 | import ( |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 220 | "bar/testutil" // also imports "foo" |
| 221 | . "foo" |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 222 | ) |
| 223 | ``` |
| 224 | |
| 225 | In this case, the test file cannot be in package foo because it uses bar/testutil, which imports foo. So we use the 'import .' form to let the file pretend to be part of package foo even though it is not. Except for this one case, do not use import . in your programs. It makes the programs much harder to read because it is unclear whether a name like Quux is a top-level identifier in the current package or in an imported package. |
| 226 | |
Jaana B. Dogan | ad8c445 | 2017-01-30 10:15:18 -0800 | [diff] [blame^] | 227 | ## In-Band Errors |
| 228 | |
| 229 | In C and similar languages, it's common for functions to return values like -1 |
| 230 | or null to signal errors or missing results: |
| 231 | |
| 232 | ```go |
| 233 | // Lookup returns the value for key or "" if there is no mapping for key. |
| 234 | func Lookup(key string) string |
| 235 | |
| 236 | // Failing to check a for an in-band error value can lead to bugs: |
| 237 | Parse(Lookup(key)) // returns "parse failure for value" instead of "no value for key" |
| 238 | ``` |
| 239 | |
| 240 | Go's support for multiple return values provides a better solution. |
| 241 | Instead requiring clients to check for an in-band error value, a function should return |
| 242 | an additional value to indicate whether its other return values are valid. This return |
| 243 | value may be an error, or a boolean when no explanation is needed. |
| 244 | It should be the final return value. |
| 245 | |
| 246 | ``` go |
| 247 | // Lookup returns the value for key or ok=false if there is no mapping for key. |
| 248 | func Lookup(key string) (value string, ok bool) |
| 249 | ``` |
| 250 | |
| 251 | This prevents the caller from using the result incorrectly: |
| 252 | |
| 253 | ``` go |
| 254 | Parse(Lookup(key)) // compile-time error |
| 255 | ``` |
| 256 | |
| 257 | And encourages more robust and readable code: |
| 258 | |
| 259 | ``` go |
| 260 | value, ok := Lookup(key) |
| 261 | if !ok { |
| 262 | return fmt.Errorf("no value for %q", key) |
| 263 | } |
| 264 | return Parse(value) |
| 265 | ``` |
| 266 | |
| 267 | This rule applies to exported functions but is also useful |
| 268 | for unexported functions. |
| 269 | |
| 270 | Return values like nil, "", 0, and -1 are fine when they are |
| 271 | valid results for a function, that is, when the caller need not |
| 272 | handle them differently from other values. |
| 273 | |
| 274 | Some standard library functions, like those in package "strings", |
| 275 | return in-band error values. This greatly simplifies string-manipulation |
| 276 | code at the cost of requiring more diligence from the programmer. |
| 277 | In general, Google Go code should return additional values for errors. |
| 278 | |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 279 | ## Indent Error Flow |
| 280 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 281 | Try to keep the normal code path at a minimal indentation, and indent the error handling, dealing with it first. This improves the readability of the code by permitting visually scanning the normal path quickly. For instance, don't write: |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 282 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 283 | ```go |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 284 | if err != nil { |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 285 | // error handling |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 286 | } else { |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 287 | // normal code |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 288 | } |
| 289 | ``` |
| 290 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 291 | Instead, write: |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 292 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 293 | ```go |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 294 | if err != nil { |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 295 | // error handling |
| 296 | return // or continue, etc. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 297 | } |
| 298 | // normal code |
| 299 | ``` |
| 300 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 301 | If the if statement has an initialization statement that, such as: |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 302 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 303 | ```go |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 304 | if x, err := f(); err != nil { |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 305 | // error handling |
| 306 | return |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 307 | } else { |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 308 | // use x |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 309 | } |
| 310 | ``` |
| 311 | |
| 312 | then this may require moving the short variable declaration to its own line: |
| 313 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 314 | ```go |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 315 | x, err := f() |
| 316 | if err != nil { |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 317 | // error handling |
| 318 | return |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 319 | } |
| 320 | // use x |
| 321 | ``` |
| 322 | |
| 323 | ## Initialisms |
| 324 | |
| 325 | Words in names that are initialisms or acronyms (e.g. "URL" or "NATO") have a consistent case. For example, "URL" should appear as "URL" or "url" (as in "urlPony", or "URLPony"), never as "Url". Here's an example: ServeHTTP not ServeHttp. |
| 326 | |
| 327 | This rule also applies to "ID" when it is short for "identifier," so write "appID" instead of "appId". |
| 328 | |
| 329 | Code generated by the protocol buffer compiler is exempt from this rule. Human-written code is held to a higher standard than machine-written code. |
| 330 | |
| 331 | ## Line Length |
| 332 | |
| 333 | There is no rigid line length limit in Go code, but avoid uncomfortably long lines. Similarly, don't add line breaks to keep lines short when they are more readable long--for example, if they are repetitive. |
| 334 | |
| 335 | Comments are typically wrapped before no more than 80 characters, not because it's a rule, but because it's more readable when viewing in an editor that might be sized to show hundreds of columns wide. Humans are better at following narrow text (e.g. columns in a newspaper) than giant walls of wide text, as a wide editor might show. Regardless, godoc should render it nicely either way. |
| 336 | |
| 337 | ## Mixed Caps |
| 338 | |
Dmitri Shuralyov | 2c403c2 | 2016-09-25 00:07:16 -0700 | [diff] [blame] | 339 | See https://golang.org/doc/effective_go.html#mixed-caps. This applies even when it breaks conventions in other languages. For example an unexported constant is `maxLength` not `MaxLength` or `MAX_LENGTH`. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 340 | |
| 341 | ## Named Result Parameters |
| 342 | |
| 343 | Consider what it will look like in godoc. Named result parameters like: |
| 344 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 345 | ```go |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 346 | func (n *Node) Parent1() (node *Node) |
| 347 | func (n *Node) Parent2() (node *Node, err error) |
| 348 | ``` |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 349 | |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 350 | will stutter in godoc; better to use: |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 351 | |
| 352 | ```go |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 353 | func (n *Node) Parent1() *Node |
| 354 | func (n *Node) Parent2() (*Node, error) |
| 355 | ``` |
| 356 | |
| 357 | On the other hand, if a function returns two or three parameters of the same type, or if the meaning of a result isn't clear from context, adding names may be useful. For example: |
| 358 | |
| 359 | ```go |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 360 | func (f *Foo) Location() (float64, float64, error) |
| 361 | ``` |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 362 | |
| 363 | is less clear than: |
| 364 | |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 365 | ```go |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 366 | // Location returns f's latitude and longitude. |
| 367 | // Negative values mean south and west, respectively. |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 368 | func (f *Foo) Location() (lat, long float64, err error) |
| 369 | ``` |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 370 | |
| 371 | Naked returns are okay if the function is a handful of lines. Once it's a medium-sized function, be explicit with your return values. Corollary: it's not worth it to name result parameters just because it enables you to use naked returns. Clarity of docs is always more important than saving a line or two in your function. |
| 372 | |
| 373 | Finally, in some cases you need to name a result parameter in order to change it in a deferred closure. That is always okay. |
| 374 | |
| 375 | ## Naked Returns |
| 376 | |
nathany | 812cb13 | 2014-12-10 22:35:33 -0800 | [diff] [blame] | 377 | See [Named Result Parameters](#named-result-parameters). |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 378 | |
| 379 | ## Package Comments |
| 380 | |
| 381 | Package comments, like all comments to be presented by godoc, must appear adjacent to the package clause, with no blank line. |
| 382 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 383 | ```go |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 384 | // Package math provides basic constants and mathematical functions. |
| 385 | package math |
| 386 | ``` |
| 387 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 388 | ```go |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 389 | /* |
| 390 | Package template implements data-driven templates for generating textual |
| 391 | output such as HTML. |
| 392 | .... |
| 393 | */ |
| 394 | package template |
| 395 | ``` |
| 396 | |
Dmitri Shuralyov | 2c403c2 | 2016-09-25 00:07:16 -0700 | [diff] [blame] | 397 | See https://golang.org/doc/effective_go.html#commentary for more information about commentary conventions. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 398 | |
| 399 | ## Package Names |
| 400 | |
Terry Liu | 0e2fe19 | 2016-10-21 22:20:03 -0700 | [diff] [blame] | 401 | All references to names in your package will be done using the package name, so you can omit that name from the identifiers. For example, if you are in package chubby, you don't need to type ChubbyFile, which clients will write as chubby.ChubbyFile. Instead, name the type File, which clients will write as chubby.File. See https://golang.org/doc/effective_go.html#package-names for more. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 402 | |
| 403 | ## Pass Values |
| 404 | |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 405 | Don't pass pointers as function arguments just to save a few bytes. If a function refers to its argument `x` only as `*x` throughout, then the argument shouldn't be a pointer. Common instances of this include passing a pointer to a string (`*string`) or a pointer to an interface value (`*io.Reader`). In both cases the value itself is a fixed size and can be passed directly. This advice does not apply to large structs, or even small structs that might grow. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 406 | |
| 407 | ## Receiver Names |
| 408 | |
Christopher Dunn | 4cb9dac | 2016-07-03 12:24:45 -0700 | [diff] [blame] | 409 | The name of a method's receiver should be a reflection of its identity; often a one or two letter abbreviation of its type suffices (such as "c" or "cl" for "Client"). Don't use generic names such as "me", "this" or "self", identifiers typical of object-oriented languages that place more emphasis on methods as opposed to functions. The name need not be as descriptive as that of a method argument, as its role is obvious and serves no documentary purpose. It can be very short as it will appear on almost every line of every method of the type; familiarity admits brevity. Be consistent, too: if you call the receiver "c" in one method, don't call it "cl" in another. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 410 | |
| 411 | ## Receiver Type |
| 412 | |
Kevin Gillette | 68ab16c | 2016-02-19 10:33:35 -0700 | [diff] [blame] | 413 | Choosing whether to use a value or pointer receiver on methods can be difficult, especially to new Go programmers. If in doubt, use a pointer, but there are times when a value receiver makes sense, usually for reasons of efficiency, such as for small unchanging structs or values of basic type. Some useful guidelines: |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 414 | |
| 415 | * If the receiver is a map, func or chan, don't use a pointer to it. |
| 416 | * If the receiver is a slice and the method doesn't reslice or reallocate the slice, don't use a pointer to it. |
| 417 | * If the method needs to mutate the receiver, the receiver must be a pointer. |
| 418 | * If the receiver is a struct that contains a sync.Mutex or similar synchronizing field, the receiver must be a pointer to avoid copying. |
| 419 | * If the receiver is a large struct or array, a pointer receiver is more efficient. How large is large? Assume it's equivalent to passing all its elements as arguments to the method. If that feels too large, it's also too large for the receiver. |
| 420 | * Can function or methods, either concurrently or when called from this method, be mutating the receiver? A value type creates a copy of the receiver when the method is invoked, so outside updates will not be applied to this receiver. If changes must be visible in the original receiver, the receiver must be a pointer. |
| 421 | * If the receiver is a struct, array or slice and any of its elements is a pointer to something that might be mutating, prefer a pointer receiver, as it will make the intention more clear to the reader. |
| 422 | * If the receiver is a small array or struct that is naturally a value type (for instance, something like the time.Time type), with no mutable fields and no pointers, or is just a simple basic type such as int or string, a value receiver makes sense. A value receiver can reduce the amount of garbage that can be generated; if a value is passed to a value method, an on-stack copy can be used instead of allocating on the heap. (The compiler tries to be smart about avoiding this allocation, but it can't always succeed.) Don't choose a value receiver type for this reason without profiling first. |
| 423 | * Finally, when in doubt, use a pointer receiver. |
| 424 | |
| 425 | ## Useful Test Failures |
| 426 | |
| 427 | Tests should fail with helpful messages saying what was wrong, with what inputs, what was actually got, and what was expected. It may be tempting to write a bunch of assertFoo helpers, but be sure your helpers produce useful error messages. Assume that the person debugging your failing test is not you, and is not your team. A typical Go test fails like: |
| 428 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 429 | ```go |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 430 | if got != tt.want { |
| 431 | t.Errorf("Foo(%q) = %d; want %d", tt.in, got, tt.want) // or Fatalf, if test can't test anything more past this point |
| 432 | } |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 433 | ``` |
| 434 | |
| 435 | Note that the order here is actual != expected, and the message uses that order too. Some test frameworks encourage writing these backwards: 0 != x, "expected 0, got x", and so on. Go does not. |
| 436 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 437 | If that seems like a lot of typing, you may want to write a [[table-driven test|TableDrivenTests]]. |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 438 | |
| 439 | Another common technique to disambiguate failing tests when using a test helper with different input is to wrap each caller with a different TestFoo function, so the test fails with that name: |
| 440 | |
nathany | 4d6a1bf | 2014-12-10 22:00:35 -0800 | [diff] [blame] | 441 | ```go |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 442 | func TestSingleValue(t *testing.T) { testHelper(t, []int{80}) } |
| 443 | func TestNoValues(t *testing.T) { testHelper(t, []int{}) } |
Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 444 | ``` |
| 445 | |
| 446 | In any case, the onus is on you to fail with a helpful message to whoever's debugging your code in the future. |
| 447 | |
| 448 | ## Variable Names |
| 449 | |
| 450 | Variable names in Go should be short rather than long. This is especially true for local variables with limited scope. Prefer c to lineCount. Prefer i to sliceIndex. |
| 451 | |
Dave Day | 0d6986a | 2014-12-10 15:02:18 +1100 | [diff] [blame] | 452 | The basic rule: the further from its declaration that a name is used, the more descriptive the name must be. For a method receiver, one or two letters is sufficient. Common variables such as loop indices and readers can be a single letter (`i`, `r`). More unusual things and global variables need more descriptive names. |