doc.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. package staticcheck
  2. import "honnef.co/go/tools/lint"
  3. var Docs = map[string]*lint.Documentation{
  4. "SA1000": &lint.Documentation{
  5. Title: `Invalid regular expression`,
  6. Since: "2017.1",
  7. },
  8. "SA1001": &lint.Documentation{
  9. Title: `Invalid template`,
  10. Since: "2017.1",
  11. },
  12. "SA1002": &lint.Documentation{
  13. Title: `Invalid format in time.Parse`,
  14. Since: "2017.1",
  15. },
  16. "SA1003": &lint.Documentation{
  17. Title: `Unsupported argument to functions in encoding/binary`,
  18. Text: `The encoding/binary package can only serialize types with known sizes.
  19. This precludes the use of the int and uint types, as their sizes
  20. differ on different architectures. Furthermore, it doesn't support
  21. serializing maps, channels, strings, or functions.
  22. Before Go 1.8, bool wasn't supported, either.`,
  23. Since: "2017.1",
  24. },
  25. "SA1004": &lint.Documentation{
  26. Title: `Suspiciously small untyped constant in time.Sleep`,
  27. Text: `The time.Sleep function takes a time.Duration as its only argument.
  28. Durations are expressed in nanoseconds. Thus, calling time.Sleep(1)
  29. will sleep for 1 nanosecond. This is a common source of bugs, as sleep
  30. functions in other languages often accept seconds or milliseconds.
  31. The time package provides constants such as time.Second to express
  32. large durations. These can be combined with arithmetic to express
  33. arbitrary durations, for example '5 * time.Second' for 5 seconds.
  34. If you truly meant to sleep for a tiny amount of time, use
  35. 'n * time.Nanosecond' to signal to staticcheck that you did mean to sleep
  36. for some amount of nanoseconds.`,
  37. Since: "2017.1",
  38. },
  39. "SA1005": &lint.Documentation{
  40. Title: `Invalid first argument to exec.Command`,
  41. Text: `os/exec runs programs directly (using variants of the fork and exec
  42. system calls on Unix systems). This shouldn't be confused with running
  43. a command in a shell. The shell will allow for features such as input
  44. redirection, pipes, and general scripting. The shell is also
  45. responsible for splitting the user's input into a program name and its
  46. arguments. For example, the equivalent to
  47. ls / /tmp
  48. would be
  49. exec.Command("ls", "/", "/tmp")
  50. If you want to run a command in a shell, consider using something like
  51. the following – but be aware that not all systems, particularly
  52. Windows, will have a /bin/sh program:
  53. exec.Command("/bin/sh", "-c", "ls | grep Awesome")`,
  54. Since: "2017.1",
  55. },
  56. "SA1006": &lint.Documentation{
  57. Title: `Printf with dynamic first argument and no further arguments`,
  58. Text: `Using fmt.Printf with a dynamic first argument can lead to unexpected
  59. output. The first argument is a format string, where certain character
  60. combinations have special meaning. If, for example, a user were to
  61. enter a string such as
  62. Interest rate: 5%
  63. and you printed it with
  64. fmt.Printf(s)
  65. it would lead to the following output:
  66. Interest rate: 5%!(NOVERB).
  67. Similarly, forming the first parameter via string concatenation with
  68. user input should be avoided for the same reason. When printing user
  69. input, either use a variant of fmt.Print, or use the %s Printf verb
  70. and pass the string as an argument.`,
  71. Since: "2017.1",
  72. },
  73. "SA1007": &lint.Documentation{
  74. Title: `Invalid URL in net/url.Parse`,
  75. Since: "2017.1",
  76. },
  77. "SA1008": &lint.Documentation{
  78. Title: `Non-canonical key in http.Header map`,
  79. Text: `Keys in http.Header maps are canonical, meaning they follow a specific
  80. combination of uppercase and lowercase letters. Methods such as
  81. http.Header.Add and http.Header.Del convert inputs into this canonical
  82. form before manipulating the map.
  83. When manipulating http.Header maps directly, as opposed to using the
  84. provided methods, care should be taken to stick to canonical form in
  85. order to avoid inconsistencies. The following piece of code
  86. demonstrates one such inconsistency:
  87. h := http.Header{}
  88. h["etag"] = []string{"1234"}
  89. h.Add("etag", "5678")
  90. fmt.Println(h)
  91. // Output:
  92. // map[Etag:[5678] etag:[1234]]
  93. The easiest way of obtaining the canonical form of a key is to use
  94. http.CanonicalHeaderKey.`,
  95. Since: "2017.1",
  96. },
  97. "SA1010": &lint.Documentation{
  98. Title: `(*regexp.Regexp).FindAll called with n == 0, which will always return zero results`,
  99. Text: `If n >= 0, the function returns at most n matches/submatches. To
  100. return all results, specify a negative number.`,
  101. Since: "2017.1",
  102. },
  103. "SA1011": &lint.Documentation{
  104. Title: `Various methods in the strings package expect valid UTF-8, but invalid input is provided`,
  105. Since: "2017.1",
  106. },
  107. "SA1012": &lint.Documentation{
  108. Title: `A nil context.Context is being passed to a function, consider using context.TODO instead`,
  109. Since: "2017.1",
  110. },
  111. "SA1013": &lint.Documentation{
  112. Title: `io.Seeker.Seek is being called with the whence constant as the first argument, but it should be the second`,
  113. Since: "2017.1",
  114. },
  115. "SA1014": &lint.Documentation{
  116. Title: `Non-pointer value passed to Unmarshal or Decode`,
  117. Since: "2017.1",
  118. },
  119. "SA1015": &lint.Documentation{
  120. Title: `Using time.Tick in a way that will leak. Consider using time.NewTicker, and only use time.Tick in tests, commands and endless functions`,
  121. Since: "2017.1",
  122. },
  123. "SA1016": &lint.Documentation{
  124. Title: `Trapping a signal that cannot be trapped`,
  125. Text: `Not all signals can be intercepted by a process. Speficially, on
  126. UNIX-like systems, the syscall.SIGKILL and syscall.SIGSTOP signals are
  127. never passed to the process, but instead handled directly by the
  128. kernel. It is therefore pointless to try and handle these signals.`,
  129. Since: "2017.1",
  130. },
  131. "SA1017": &lint.Documentation{
  132. Title: `Channels used with os/signal.Notify should be buffered`,
  133. Text: `The os/signal package uses non-blocking channel sends when delivering
  134. signals. If the receiving end of the channel isn't ready and the
  135. channel is either unbuffered or full, the signal will be dropped. To
  136. avoid missing signals, the channel should be buffered and of the
  137. appropriate size. For a channel used for notification of just one
  138. signal value, a buffer of size 1 is sufficient.`,
  139. Since: "2017.1",
  140. },
  141. "SA1018": &lint.Documentation{
  142. Title: `strings.Replace called with n == 0, which does nothing`,
  143. Text: `With n == 0, zero instances will be replaced. To replace all
  144. instances, use a negative number, or use strings.ReplaceAll.`,
  145. Since: "2017.1",
  146. },
  147. "SA1019": &lint.Documentation{
  148. Title: `Using a deprecated function, variable, constant or field`,
  149. Since: "2017.1",
  150. },
  151. "SA1020": &lint.Documentation{
  152. Title: `Using an invalid host:port pair with a net.Listen-related function`,
  153. Since: "2017.1",
  154. },
  155. "SA1021": &lint.Documentation{
  156. Title: `Using bytes.Equal to compare two net.IP`,
  157. Text: `A net.IP stores an IPv4 or IPv6 address as a slice of bytes. The
  158. length of the slice for an IPv4 address, however, can be either 4 or
  159. 16 bytes long, using different ways of representing IPv4 addresses. In
  160. order to correctly compare two net.IPs, the net.IP.Equal method should
  161. be used, as it takes both representations into account.`,
  162. Since: "2017.1",
  163. },
  164. "SA1023": &lint.Documentation{
  165. Title: `Modifying the buffer in an io.Writer implementation`,
  166. Text: `Write must not modify the slice data, even temporarily.`,
  167. Since: "2017.1",
  168. },
  169. "SA1024": &lint.Documentation{
  170. Title: `A string cutset contains duplicate characters`,
  171. Text: `The strings.TrimLeft and strings.TrimRight functions take cutsets, not
  172. prefixes. A cutset is treated as a set of characters to remove from a
  173. string. For example,
  174. strings.TrimLeft("42133word", "1234"))
  175. will result in the string "word" – any characters that are 1, 2, 3 or
  176. 4 are cut from the left of the string.
  177. In order to remove one string from another, use strings.TrimPrefix instead.`,
  178. Since: "2017.1",
  179. },
  180. "SA1025": &lint.Documentation{
  181. Title: `It is not possible to use (*time.Timer).Reset's return value correctly`,
  182. Since: "2019.1",
  183. },
  184. "SA1026": &lint.Documentation{
  185. Title: `Cannot marshal channels or functions`,
  186. Since: "2019.2",
  187. },
  188. "SA1027": &lint.Documentation{
  189. Title: `Atomic access to 64-bit variable must be 64-bit aligned`,
  190. Text: `On ARM, x86-32, and 32-bit MIPS, it is the caller's responsibility to
  191. arrange for 64-bit alignment of 64-bit words accessed atomically. The
  192. first word in a variable or in an allocated struct, array, or slice
  193. can be relied upon to be 64-bit aligned.
  194. You can use the structlayout tool to inspect the alignment of fields
  195. in a struct.`,
  196. Since: "2019.2",
  197. },
  198. "SA2000": &lint.Documentation{
  199. Title: `sync.WaitGroup.Add called inside the goroutine, leading to a race condition`,
  200. Since: "2017.1",
  201. },
  202. "SA2001": &lint.Documentation{
  203. Title: `Empty critical section, did you mean to defer the unlock?`,
  204. Text: `Empty critical sections of the kind
  205. mu.Lock()
  206. mu.Unlock()
  207. are very often a typo, and the following was intended instead:
  208. mu.Lock()
  209. defer mu.Unlock()
  210. Do note that sometimes empty critical sections can be useful, as a
  211. form of signaling to wait on another goroutine. Many times, there are
  212. simpler ways of achieving the same effect. When that isn't the case,
  213. the code should be amply commented to avoid confusion. Combining such
  214. comments with a //lint:ignore directive can be used to suppress this
  215. rare false positive.`,
  216. Since: "2017.1",
  217. },
  218. "SA2002": &lint.Documentation{
  219. Title: `Called testing.T.FailNow or SkipNow in a goroutine, which isn't allowed`,
  220. Since: "2017.1",
  221. },
  222. "SA2003": &lint.Documentation{
  223. Title: `Deferred Lock right after locking, likely meant to defer Unlock instead`,
  224. Since: "2017.1",
  225. },
  226. "SA3000": &lint.Documentation{
  227. Title: `TestMain doesn't call os.Exit, hiding test failures`,
  228. Text: `Test executables (and in turn 'go test') exit with a non-zero status
  229. code if any tests failed. When specifying your own TestMain function,
  230. it is your responsibility to arrange for this, by calling os.Exit with
  231. the correct code. The correct code is returned by (*testing.M).Run, so
  232. the usual way of implementing TestMain is to end it with
  233. os.Exit(m.Run()).`,
  234. Since: "2017.1",
  235. },
  236. "SA3001": &lint.Documentation{
  237. Title: `Assigning to b.N in benchmarks distorts the results`,
  238. Text: `The testing package dynamically sets b.N to improve the reliability of
  239. benchmarks and uses it in computations to determine the duration of a
  240. single operation. Benchmark code must not alter b.N as this would
  241. falsify results.`,
  242. Since: "2017.1",
  243. },
  244. "SA4000": &lint.Documentation{
  245. Title: `Boolean expression has identical expressions on both sides`,
  246. Since: "2017.1",
  247. },
  248. "SA4001": &lint.Documentation{
  249. Title: `&*x gets simplified to x, it does not copy x`,
  250. Since: "2017.1",
  251. },
  252. "SA4002": &lint.Documentation{
  253. Title: `Comparing strings with known different sizes has predictable results`,
  254. Since: "2017.1",
  255. },
  256. "SA4003": &lint.Documentation{
  257. Title: `Comparing unsigned values against negative values is pointless`,
  258. Since: "2017.1",
  259. },
  260. "SA4004": &lint.Documentation{
  261. Title: `The loop exits unconditionally after one iteration`,
  262. Since: "2017.1",
  263. },
  264. "SA4005": &lint.Documentation{
  265. Title: `Field assignment that will never be observed. Did you mean to use a pointer receiver?`,
  266. Since: "2017.1",
  267. },
  268. "SA4006": &lint.Documentation{
  269. Title: `A value assigned to a variable is never read before being overwritten. Forgotten error check or dead code?`,
  270. Since: "2017.1",
  271. },
  272. "SA4008": &lint.Documentation{
  273. Title: `The variable in the loop condition never changes, are you incrementing the wrong variable?`,
  274. Since: "2017.1",
  275. },
  276. "SA4009": &lint.Documentation{
  277. Title: `A function argument is overwritten before its first use`,
  278. Since: "2017.1",
  279. },
  280. "SA4010": &lint.Documentation{
  281. Title: `The result of append will never be observed anywhere`,
  282. Since: "2017.1",
  283. },
  284. "SA4011": &lint.Documentation{
  285. Title: `Break statement with no effect. Did you mean to break out of an outer loop?`,
  286. Since: "2017.1",
  287. },
  288. "SA4012": &lint.Documentation{
  289. Title: `Comparing a value against NaN even though no value is equal to NaN`,
  290. Since: "2017.1",
  291. },
  292. "SA4013": &lint.Documentation{
  293. Title: `Negating a boolean twice (!!b) is the same as writing b. This is either redundant, or a typo.`,
  294. Since: "2017.1",
  295. },
  296. "SA4014": &lint.Documentation{
  297. Title: `An if/else if chain has repeated conditions and no side-effects; if the condition didn't match the first time, it won't match the second time, either`,
  298. Since: "2017.1",
  299. },
  300. "SA4015": &lint.Documentation{
  301. Title: `Calling functions like math.Ceil on floats converted from integers doesn't do anything useful`,
  302. Since: "2017.1",
  303. },
  304. "SA4016": &lint.Documentation{
  305. Title: `Certain bitwise operations, such as x ^ 0, do not do anything useful`,
  306. Since: "2017.1",
  307. },
  308. "SA4017": &lint.Documentation{
  309. Title: `A pure function's return value is discarded, making the call pointless`,
  310. Since: "2017.1",
  311. },
  312. "SA4018": &lint.Documentation{
  313. Title: `Self-assignment of variables`,
  314. Since: "2017.1",
  315. },
  316. "SA4019": &lint.Documentation{
  317. Title: `Multiple, identical build constraints in the same file`,
  318. Since: "2017.1",
  319. },
  320. "SA4020": &lint.Documentation{
  321. Title: `Unreachable case clause in a type switch`,
  322. Text: `In a type switch like the following
  323. type T struct{}
  324. func (T) Read(b []byte) (int, error) { return 0, nil }
  325. var v interface{} = T{}
  326. switch v.(type) {
  327. case io.Reader:
  328. // ...
  329. case T:
  330. // unreachable
  331. }
  332. the second case clause can never be reached because T implements
  333. io.Reader and case clauses are evaluated in source order.
  334. Another example:
  335. type T struct{}
  336. func (T) Read(b []byte) (int, error) { return 0, nil }
  337. func (T) Close() error { return nil }
  338. var v interface{} = T{}
  339. switch v.(type) {
  340. case io.Reader:
  341. // ...
  342. case io.ReadCloser:
  343. // unreachable
  344. }
  345. Even though T has a Close method and thus implements io.ReadCloser,
  346. io.Reader will always match first. The method set of io.Reader is a
  347. subset of io.ReadCloser. Thus it is impossible to match the second
  348. case without matching the first case.
  349. Structurally equivalent interfaces
  350. A special case of the previous example are structurally identical
  351. interfaces. Given these declarations
  352. type T error
  353. type V error
  354. func doSomething() error {
  355. err, ok := doAnotherThing()
  356. if ok {
  357. return T(err)
  358. }
  359. return U(err)
  360. }
  361. the following type switch will have an unreachable case clause:
  362. switch doSomething().(type) {
  363. case T:
  364. // ...
  365. case V:
  366. // unreachable
  367. }
  368. T will always match before V because they are structurally equivalent
  369. and therefore doSomething()'s return value implements both.`,
  370. Since: "2019.2",
  371. },
  372. "SA4021": &lint.Documentation{
  373. Title: `x = append(y) is equivalent to x = y`,
  374. Since: "2019.2",
  375. },
  376. "SA5000": &lint.Documentation{
  377. Title: `Assignment to nil map`,
  378. Since: "2017.1",
  379. },
  380. "SA5001": &lint.Documentation{
  381. Title: `Defering Close before checking for a possible error`,
  382. Since: "2017.1",
  383. },
  384. "SA5002": &lint.Documentation{
  385. Title: `The empty for loop (for {}) spins and can block the scheduler`,
  386. Since: "2017.1",
  387. },
  388. "SA5003": &lint.Documentation{
  389. Title: `Defers in infinite loops will never execute`,
  390. Text: `Defers are scoped to the surrounding function, not the surrounding
  391. block. In a function that never returns, i.e. one containing an
  392. infinite loop, defers will never execute.`,
  393. Since: "2017.1",
  394. },
  395. "SA5004": &lint.Documentation{
  396. Title: `for { select { ... with an empty default branch spins`,
  397. Since: "2017.1",
  398. },
  399. "SA5005": &lint.Documentation{
  400. Title: `The finalizer references the finalized object, preventing garbage collection`,
  401. Text: `A finalizer is a function associated with an object that runs when the
  402. garbage collector is ready to collect said object, that is when the
  403. object is no longer referenced by anything.
  404. If the finalizer references the object, however, it will always remain
  405. as the final reference to that object, preventing the garbage
  406. collector from collecting the object. The finalizer will never run,
  407. and the object will never be collected, leading to a memory leak. That
  408. is why the finalizer should instead use its first argument to operate
  409. on the object. That way, the number of references can temporarily go
  410. to zero before the object is being passed to the finalizer.`,
  411. Since: "2017.1",
  412. },
  413. "SA5006": &lint.Documentation{
  414. Title: `Slice index out of bounds`,
  415. Since: "2017.1",
  416. },
  417. "SA5007": &lint.Documentation{
  418. Title: `Infinite recursive call`,
  419. Text: `A function that calls itself recursively needs to have an exit
  420. condition. Otherwise it will recurse forever, until the system runs
  421. out of memory.
  422. This issue can be caused by simple bugs such as forgetting to add an
  423. exit condition. It can also happen "on purpose". Some languages have
  424. tail call optimization which makes certain infinite recursive calls
  425. safe to use. Go, however, does not implement TCO, and as such a loop
  426. should be used instead.`,
  427. Since: "2017.1",
  428. },
  429. "SA5008": &lint.Documentation{
  430. Title: `Invalid struct tag`,
  431. Since: "2019.2",
  432. },
  433. "SA5009": &lint.Documentation{
  434. Title: `Invalid Printf call`,
  435. Since: "2019.2",
  436. },
  437. "SA6000": &lint.Documentation{
  438. Title: `Using regexp.Match or related in a loop, should use regexp.Compile`,
  439. Since: "2017.1",
  440. },
  441. "SA6001": &lint.Documentation{
  442. Title: `Missing an optimization opportunity when indexing maps by byte slices`,
  443. Text: `Map keys must be comparable, which precludes the use of byte slices.
  444. This usually leads to using string keys and converting byte slices to
  445. strings.
  446. Normally, a conversion of a byte slice to a string needs to copy the data and
  447. causes allocations. The compiler, however, recognizes m[string(b)] and
  448. uses the data of b directly, without copying it, because it knows that
  449. the data can't change during the map lookup. This leads to the
  450. counter-intuitive situation that
  451. k := string(b)
  452. println(m[k])
  453. println(m[k])
  454. will be less efficient than
  455. println(m[string(b)])
  456. println(m[string(b)])
  457. because the first version needs to copy and allocate, while the second
  458. one does not.
  459. For some history on this optimization, check out commit
  460. f5f5a8b6209f84961687d993b93ea0d397f5d5bf in the Go repository.`,
  461. Since: "2017.1",
  462. },
  463. "SA6002": &lint.Documentation{
  464. Title: `Storing non-pointer values in sync.Pool allocates memory`,
  465. Text: `A sync.Pool is used to avoid unnecessary allocations and reduce the
  466. amount of work the garbage collector has to do.
  467. When passing a value that is not a pointer to a function that accepts
  468. an interface, the value needs to be placed on the heap, which means an
  469. additional allocation. Slices are a common thing to put in sync.Pools,
  470. and they're structs with 3 fields (length, capacity, and a pointer to
  471. an array). In order to avoid the extra allocation, one should store a
  472. pointer to the slice instead.
  473. See the comments on https://go-review.googlesource.com/c/go/+/24371
  474. that discuss this problem.`,
  475. Since: "2017.1",
  476. },
  477. "SA6003": &lint.Documentation{
  478. Title: `Converting a string to a slice of runes before ranging over it`,
  479. Text: `You may want to loop over the runes in a string. Instead of converting
  480. the string to a slice of runes and looping over that, you can loop
  481. over the string itself. That is,
  482. for _, r := range s {}
  483. and
  484. for _, r := range []rune(s) {}
  485. will yield the same values. The first version, however, will be faster
  486. and avoid unnecessary memory allocations.
  487. Do note that if you are interested in the indices, ranging over a
  488. string and over a slice of runes will yield different indices. The
  489. first one yields byte offsets, while the second one yields indices in
  490. the slice of runes.`,
  491. Since: "2017.1",
  492. },
  493. "SA6005": &lint.Documentation{
  494. Title: `Inefficient string comparison with strings.ToLower or strings.ToUpper`,
  495. Text: `Converting two strings to the same case and comparing them like so
  496. if strings.ToLower(s1) == strings.ToLower(s2) {
  497. ...
  498. }
  499. is significantly more expensive than comparing them with
  500. strings.EqualFold(s1, s2). This is due to memory usage as well as
  501. computational complexity.
  502. strings.ToLower will have to allocate memory for the new strings, as
  503. well as convert both strings fully, even if they differ on the very
  504. first byte. strings.EqualFold, on the other hand, compares the strings
  505. one character at a time. It doesn't need to create two intermediate
  506. strings and can return as soon as the first non-matching character has
  507. been found.
  508. For a more in-depth explanation of this issue, see
  509. https://blog.digitalocean.com/how-to-efficiently-compare-strings-in-go/`,
  510. Since: "2019.2",
  511. },
  512. "SA9001": &lint.Documentation{
  513. Title: `Defers in range loops may not run when you expect them to`,
  514. Since: "2017.1",
  515. },
  516. "SA9002": &lint.Documentation{
  517. Title: `Using a non-octal os.FileMode that looks like it was meant to be in octal.`,
  518. Since: "2017.1",
  519. },
  520. "SA9003": &lint.Documentation{
  521. Title: `Empty body in an if or else branch`,
  522. Since: "2017.1",
  523. },
  524. "SA9004": &lint.Documentation{
  525. Title: `Only the first constant has an explicit type`,
  526. Text: `In a constant declaration such as the following:
  527. const (
  528. First byte = 1
  529. Second = 2
  530. )
  531. the constant Second does not have the same type as the constant First.
  532. This construct shouldn't be confused with
  533. const (
  534. First byte = iota
  535. Second
  536. )
  537. where First and Second do indeed have the same type. The type is only
  538. passed on when no explicit value is assigned to the constant.
  539. When declaring enumerations with explicit values it is therefore
  540. important not to write
  541. const (
  542. EnumFirst EnumType = 1
  543. EnumSecond = 2
  544. EnumThird = 3
  545. )
  546. This discrepancy in types can cause various confusing behaviors and
  547. bugs.
  548. Wrong type in variable declarations
  549. The most obvious issue with such incorrect enumerations expresses
  550. itself as a compile error:
  551. package pkg
  552. const (
  553. EnumFirst uint8 = 1
  554. EnumSecond = 2
  555. )
  556. func fn(useFirst bool) {
  557. x := EnumSecond
  558. if useFirst {
  559. x = EnumFirst
  560. }
  561. }
  562. fails to compile with
  563. ./const.go:11:5: cannot use EnumFirst (type uint8) as type int in assignment
  564. Losing method sets
  565. A more subtle issue occurs with types that have methods and optional
  566. interfaces. Consider the following:
  567. package main
  568. import "fmt"
  569. type Enum int
  570. func (e Enum) String() string {
  571. return "an enum"
  572. }
  573. const (
  574. EnumFirst Enum = 1
  575. EnumSecond = 2
  576. )
  577. func main() {
  578. fmt.Println(EnumFirst)
  579. fmt.Println(EnumSecond)
  580. }
  581. This code will output
  582. an enum
  583. 2
  584. as EnumSecond has no explicit type, and thus defaults to int.`,
  585. Since: "2019.1",
  586. },
  587. "SA9005": &lint.Documentation{
  588. Title: `Trying to marshal a struct with no public fields nor custom marshaling`,
  589. Text: `The encoding/json and encoding/xml packages only operate on exported
  590. fields in structs, not unexported ones. It is usually an error to try
  591. to (un)marshal structs that only consist of unexported fields.
  592. This check will not flag calls involving types that define custom
  593. marshaling behavior, e.g. via MarshalJSON methods. It will also not
  594. flag empty structs.`,
  595. Since: "2019.2",
  596. },
  597. }