Debian Codegraph @

gopls/doc/analyzers.md

raw symbols SCIP
1 ---
2 title: "Gopls: Analyzers"
3 ---
4
5 <!-- No Table of Contents: GitHub's Markdown renderer synthesizes it. -->
6
7 Gopls contains a driver for pluggable, modular static
8 [analyzers](https://pkg.go.dev/golang.org/x/tools/go/analysis#hdr-Analyzer),
9 such as those used by [go vet](https://pkg.go.dev/cmd/vet).
10
11 Most analyzers report mistakes in your code;
12 some suggest "quick fixes" that can be directly applied in your editor.
13 Every time you edit your code, gopls re-runs its analyzers.
14 Analyzer diagnostics help you detect bugs sooner,
15 before you run your tests, or even before you save your files.
16
17 This document describes the suite of analyzers available in gopls,
18 which aggregates analyzers from a variety of sources:
19
20 - all the usual bug-finding analyzers from the `go vet` suite (e.g. `printf`; see [`go tool vet help`](https://pkg.go.dev/cmd/vet) for the complete list);
21 - a number of analyzers with more substantial dependencies that prevent them from being used in `go vet` (e.g. `nilness`);
22 - analyzers that augment compilation errors by suggesting quick fixes to common mistakes (e.g. `fillreturns`); and
23 - a handful of analyzers that suggest possible style improvements (e.g. `simplifyrange`).
24
25 To enable or disable analyzers, use the [analyses](settings.md#analyses) setting.
26
27 In addition, gopls includes the [`staticcheck` suite](https://staticcheck.dev/docs/checks).
28 When the [`staticcheck`](settings.md#staticcheck`) boolean option is
29 unset, slightly more than half of these analyzers are enabled by
30 default; this subset has been chosen for precision and efficiency. Set
31 `staticcheck` to `true` to enable the complete set, or to `false` to
32 disable the complete set.
33
34 Staticcheck analyzers, like all other analyzers, can be explicitly
35 enabled or disabled using the `analyzers` configuration setting; this
36 setting takes precedence over the `staticcheck` setting, so,
37 regardless of what value of `staticcheck` you use (true/false/unset),
38 you can make adjustments to your preferred set of analyzers.
39
40
41 <!-- BEGIN Analyzers: DO NOT MANUALLY EDIT THIS SECTION -->
42 <a id='QF1001'></a>
43 ## `QF1001`: Apply De Morgan's law
44
45 Available since
46
47 2021.1
48
49
50 Default: off. Enable by setting `"analyses": {"QF1001": true}`.
51
52 Package documentation: [QF1001](https://staticcheck.dev/docs/checks/#QF1001)
53
54 <a id='QF1002'></a>
55 ## `QF1002`: Convert untagged switch to tagged switch
56
57 An untagged switch that compares a single variable against a series of values can be replaced with a tagged switch.
58
59 Before:
60
61 switch {
62 case x == 1 || x == 2, x == 3:
63 ...
64 case x == 4:
65 ...
66 default:
67 ...
68 }
69
70 After:
71
72 switch x {
73 case 1, 2, 3:
74 ...
75 case 4:
76 ...
77 default:
78 ...
79 }
80
81 Available since
82
83 2021.1
84
85
86 Default: on.
87
88 Package documentation: [QF1002](https://staticcheck.dev/docs/checks/#QF1002)
89
90 <a id='QF1003'></a>
91 ## `QF1003`: Convert if/else-if chain to tagged switch
92
93 A series of if/else-if checks comparing the same variable against values can be replaced with a tagged switch.
94
95 Before:
96
97 if x == 1 || x == 2 {
98 ...
99 } else if x == 3 {
100 ...
101 } else {
102 ...
103 }
104
105 After:
106
107 switch x {
108 case 1, 2:
109 ...
110 case 3:
111 ...
112 default:
113 ...
114 }
115
116 Available since
117
118 2021.1
119
120
121 Default: on.
122
123 Package documentation: [QF1003](https://staticcheck.dev/docs/checks/#QF1003)
124
125 <a id='QF1004'></a>
126 ## `QF1004`: Use strings.ReplaceAll instead of strings.Replace with n == -1
127
128 Available since
129
130 2021.1
131
132
133 Default: on.
134
135 Package documentation: [QF1004](https://staticcheck.dev/docs/checks/#QF1004)
136
137 <a id='QF1005'></a>
138 ## `QF1005`: Expand call to math.Pow
139
140 Some uses of math.Pow can be simplified to basic multiplication.
141
142 Before:
143
144 math.Pow(x, 2)
145
146 After:
147
148 x * x
149
150 Available since
151
152 2021.1
153
154
155 Default: off. Enable by setting `"analyses": {"QF1005": true}`.
156
157 Package documentation: [QF1005](https://staticcheck.dev/docs/checks/#QF1005)
158
159 <a id='QF1006'></a>
160 ## `QF1006`: Lift if+break into loop condition
161
162 Before:
163
164 for {
165 if done {
166 break
167 }
168 ...
169 }
170
171 After:
172
173 for !done {
174 ...
175 }
176
177 Available since
178
179 2021.1
180
181
182 Default: off. Enable by setting `"analyses": {"QF1006": true}`.
183
184 Package documentation: [QF1006](https://staticcheck.dev/docs/checks/#QF1006)
185
186 <a id='QF1007'></a>
187 ## `QF1007`: Merge conditional assignment into variable declaration
188
189 Before:
190
191 x := false
192 if someCondition {
193 x = true
194 }
195
196 After:
197
198 x := someCondition
199
200 Available since
201
202 2021.1
203
204
205 Default: off. Enable by setting `"analyses": {"QF1007": true}`.
206
207 Package documentation: [QF1007](https://staticcheck.dev/docs/checks/#QF1007)
208
209 <a id='QF1008'></a>
210 ## `QF1008`: Omit embedded fields from selector expression
211
212 Available since
213
214 2021.1
215
216
217 Default: off. Enable by setting `"analyses": {"QF1008": true}`.
218
219 Package documentation: [QF1008](https://staticcheck.dev/docs/checks/#QF1008)
220
221 <a id='QF1009'></a>
222 ## `QF1009`: Use time.Time.Equal instead of == operator
223
224 Available since
225
226 2021.1
227
228
229 Default: on.
230
231 Package documentation: [QF1009](https://staticcheck.dev/docs/checks/#QF1009)
232
233 <a id='QF1010'></a>
234 ## `QF1010`: Convert slice of bytes to string when printing it
235
236 Available since
237
238 2021.1
239
240
241 Default: on.
242
243 Package documentation: [QF1010](https://staticcheck.dev/docs/checks/#QF1010)
244
245 <a id='QF1011'></a>
246 ## `QF1011`: Omit redundant type from variable declaration
247
248 Available since
249
250 2021.1
251
252
253 Default: off. Enable by setting `"analyses": {"QF1011": true}`.
254
255 Package documentation: [QF1011](https://staticcheck.dev/docs/checks/#)
256
257 <a id='QF1012'></a>
258 ## `QF1012`: Use fmt.Fprintf(x, ...) instead of x.Write(fmt.Sprintf(...))
259
260 Available since
261
262 2022.1
263
264
265 Default: on.
266
267 Package documentation: [QF1012](https://staticcheck.dev/docs/checks/#QF1012)
268
269 <a id='S1000'></a>
270 ## `S1000`: Use plain channel send or receive instead of single-case select
271
272 Select statements with a single case can be replaced with a simple send or receive.
273
274 Before:
275
276 select {
277 case x := <-ch:
278 fmt.Println(x)
279 }
280
281 After:
282
283 x := <-ch
284 fmt.Println(x)
285
286 Available since
287
288 2017.1
289
290
291 Default: on.
292
293 Package documentation: [S1000](https://staticcheck.dev/docs/checks/#S1000)
294
295 <a id='S1001'></a>
296 ## `S1001`: Replace for loop with call to copy
297
298 Use copy() for copying elements from one slice to another. For arrays of identical size, you can use simple assignment.
299
300 Before:
301
302 for i, x := range src {
303 dst[i] = x
304 }
305
306 After:
307
308 copy(dst, src)
309
310 Available since
311
312 2017.1
313
314
315 Default: on.
316
317 Package documentation: [S1001](https://staticcheck.dev/docs/checks/#S1001)
318
319 <a id='S1002'></a>
320 ## `S1002`: Omit comparison with boolean constant
321
322 Before:
323
324 if x == true {}
325
326 After:
327
328 if x {}
329
330 Available since
331
332 2017.1
333
334
335 Default: off. Enable by setting `"analyses": {"S1002": true}`.
336
337 Package documentation: [S1002](https://staticcheck.dev/docs/checks/#S1002)
338
339 <a id='S1003'></a>
340 ## `S1003`: Replace call to strings.Index with strings.Contains
341
342 Before:
343
344 if strings.Index(x, y) != -1 {}
345
346 After:
347
348 if strings.Contains(x, y) {}
349
350 Available since
351
352 2017.1
353
354
355 Default: on.
356
357 Package documentation: [S1003](https://staticcheck.dev/docs/checks/#S1003)
358
359 <a id='S1004'></a>
360 ## `S1004`: Replace call to bytes.Compare with bytes.Equal
361
362 Before:
363
364 if bytes.Compare(x, y) == 0 {}
365
366 After:
367
368 if bytes.Equal(x, y) {}
369
370 Available since
371
372 2017.1
373
374
375 Default: on.
376
377 Package documentation: [S1004](https://staticcheck.dev/docs/checks/#S1004)
378
379 <a id='S1005'></a>
380 ## `S1005`: Drop unnecessary use of the blank identifier
381
382 In many cases, assigning to the blank identifier is unnecessary.
383
384 Before:
385
386 for _ = range s {}
387 x, _ = someMap[key]
388 _ = <-ch
389
390 After:
391
392 for range s{}
393 x = someMap[key]
394 <-ch
395
396 Available since
397
398 2017.1
399
400
401 Default: off. Enable by setting `"analyses": {"S1005": true}`.
402
403 Package documentation: [S1005](https://staticcheck.dev/docs/checks/#S1005)
404
405 <a id='S1006'></a>
406 ## `S1006`: Use 'for { ... }' for infinite loops
407
408 For infinite loops, using for { ... } is the most idiomatic choice.
409
410 Available since
411
412 2017.1
413
414
415 Default: off. Enable by setting `"analyses": {"S1006": true}`.
416
417 Package documentation: [S1006](https://staticcheck.dev/docs/checks/#S1006)
418
419 <a id='S1007'></a>
420 ## `S1007`: Simplify regular expression by using raw string literal
421
422 Raw string literals use backticks instead of quotation marks and do not support any escape sequences. This means that the backslash can be used freely, without the need of escaping.
423
424 Since regular expressions have their own escape sequences, raw strings can improve their readability.
425
426 Before:
427
428 regexp.Compile("\\A(\\w+) profile: total \\d+\\n\\z")
429
430 After:
431
432 regexp.Compile(`\A(\w+) profile: total \d+\n\z`)
433
434 Available since
435
436 2017.1
437
438
439 Default: on.
440
441 Package documentation: [S1007](https://staticcheck.dev/docs/checks/#S1007)
442
443 <a id='S1008'></a>
444 ## `S1008`: Simplify returning boolean expression
445
446 Before:
447
448 if <expr> {
449 return true
450 }
451 return false
452
453 After:
454
455 return <expr>
456
457 Available since
458
459 2017.1
460
461
462 Default: off. Enable by setting `"analyses": {"S1008": true}`.
463
464 Package documentation: [S1008](https://staticcheck.dev/docs/checks/#S1008)
465
466 <a id='S1009'></a>
467 ## `S1009`: Omit redundant nil check on slices, maps, and channels
468
469 The len function is defined for all slices, maps, and channels, even nil ones, which have a length of zero. It is not necessary to check for nil before checking that their length is not zero.
470
471 Before:
472
473 if x != nil && len(x) != 0 {}
474
475 After:
476
477 if len(x) != 0 {}
478
479 Available since
480
481 2017.1
482
483
484 Default: on.
485
486 Package documentation: [S1009](https://staticcheck.dev/docs/checks/#S1009)
487
488 <a id='S1010'></a>
489 ## `S1010`: Omit default slice index
490
491 When slicing, the second index defaults to the length of the value, making s\[n:len(s)] and s\[n:] equivalent.
492
493 Available since
494
495 2017.1
496
497
498 Default: on.
499
500 Package documentation: [S1010](https://staticcheck.dev/docs/checks/#S1010)
501
502 <a id='S1011'></a>
503 ## `S1011`: Use a single append to concatenate two slices
504
505 Before:
506
507 for _, e := range y {
508 x = append(x, e)
509 }
510
511 for i := range y {
512 x = append(x, y[i])
513 }
514
515 for i := range y {
516 v := y[i]
517 x = append(x, v)
518 }
519
520 After:
521
522 x = append(x, y...)
523 x = append(x, y...)
524 x = append(x, y...)
525
526 Available since
527
528 2017.1
529
530
531 Default: off. Enable by setting `"analyses": {"S1011": true}`.
532
533 Package documentation: [S1011](https://staticcheck.dev/docs/checks/#S1011)
534
535 <a id='S1012'></a>
536 ## `S1012`: Replace time.Now().Sub(x) with time.Since(x)
537
538 The time.Since helper has the same effect as using time.Now().Sub(x) but is easier to read.
539
540 Before:
541
542 time.Now().Sub(x)
543
544 After:
545
546 time.Since(x)
547
548 Available since
549
550 2017.1
551
552
553 Default: on.
554
555 Package documentation: [S1012](https://staticcheck.dev/docs/checks/#S1012)
556
557 <a id='S1016'></a>
558 ## `S1016`: Use a type conversion instead of manually copying struct fields
559
560 Two struct types with identical fields can be converted between each other. In older versions of Go, the fields had to have identical struct tags. Since Go 1.8, however, struct tags are ignored during conversions. It is thus not necessary to manually copy every field individually.
561
562 Before:
563
564 var x T1
565 y := T2{
566 Field1: x.Field1,
567 Field2: x.Field2,
568 }
569
570 After:
571
572 var x T1
573 y := T2(x)
574
575 Available since
576
577 2017.1
578
579
580 Default: off. Enable by setting `"analyses": {"S1016": true}`.
581
582 Package documentation: [S1016](https://staticcheck.dev/docs/checks/#S1016)
583
584 <a id='S1017'></a>
585 ## `S1017`: Replace manual trimming with strings.TrimPrefix
586
587 Instead of using strings.HasPrefix and manual slicing, use the strings.TrimPrefix function. If the string doesn't start with the prefix, the original string will be returned. Using strings.TrimPrefix reduces complexity, and avoids common bugs, such as off-by-one mistakes.
588
589 Before:
590
591 if strings.HasPrefix(str, prefix) {
592 str = str[len(prefix):]
593 }
594
595 After:
596
597 str = strings.TrimPrefix(str, prefix)
598
599 Available since
600
601 2017.1
602
603
604 Default: on.
605
606 Package documentation: [S1017](https://staticcheck.dev/docs/checks/#S1017)
607
608 <a id='S1018'></a>
609 ## `S1018`: Use 'copy' for sliding elements
610
611 copy() permits using the same source and destination slice, even with overlapping ranges. This makes it ideal for sliding elements in a slice.
612
613 Before:
614
615 for i := 0; i < n; i++ {
616 bs[i] = bs[offset+i]
617 }
618
619 After:
620
621 copy(bs[:n], bs[offset:])
622
623 Available since
624
625 2017.1
626
627
628 Default: on.
629
630 Package documentation: [S1018](https://staticcheck.dev/docs/checks/#S1018)
631
632 <a id='S1019'></a>
633 ## `S1019`: Simplify 'make' call by omitting redundant arguments
634
635 The 'make' function has default values for the length and capacity arguments. For channels, the length defaults to zero, and for slices, the capacity defaults to the length.
636
637 Available since
638
639 2017.1
640
641
642 Default: on.
643
644 Package documentation: [S1019](https://staticcheck.dev/docs/checks/#S1019)
645
646 <a id='S1020'></a>
647 ## `S1020`: Omit redundant nil check in type assertion
648
649 Before:
650
651 if _, ok := i.(T); ok && i != nil {}
652
653 After:
654
655 if _, ok := i.(T); ok {}
656
657 Available since
658
659 2017.1
660
661
662 Default: on.
663
664 Package documentation: [S1020](https://staticcheck.dev/docs/checks/#S1020)
665
666 <a id='S1021'></a>
667 ## `S1021`: Merge variable declaration and assignment
668
669 Before:
670
671 var x uint
672 x = 1
673
674 After:
675
676 var x uint = 1
677
678 Available since
679
680 2017.1
681
682
683 Default: off. Enable by setting `"analyses": {"S1021": true}`.
684
685 Package documentation: [S1021](https://staticcheck.dev/docs/checks/#S1021)
686
687 <a id='S1023'></a>
688 ## `S1023`: Omit redundant control flow
689
690 Functions that have no return value do not need a return statement as the final statement of the function.
691
692 Switches in Go do not have automatic fallthrough, unlike languages like C. It is not necessary to have a break statement as the final statement in a case block.
693
694 Available since
695
696 2017.1
697
698
699 Default: on.
700
701 Package documentation: [S1023](https://staticcheck.dev/docs/checks/#S1023)
702
703 <a id='S1024'></a>
704 ## `S1024`: Replace x.Sub(time.Now()) with time.Until(x)
705
706 The time.Until helper has the same effect as using x.Sub(time.Now()) but is easier to read.
707
708 Before:
709
710 x.Sub(time.Now())
711
712 After:
713
714 time.Until(x)
715
716 Available since
717
718 2017.1
719
720
721 Default: on.
722
723 Package documentation: [S1024](https://staticcheck.dev/docs/checks/#S1024)
724
725 <a id='S1025'></a>
726 ## `S1025`: Don't use fmt.Sprintf("%s", x) unnecessarily
727
728 In many instances, there are easier and more efficient ways of getting a value's string representation. Whenever a value's underlying type is a string already, or the type has a String method, they should be used directly.
729
730 Given the following shared definitions
731
732 type T1 string
733 type T2 int
734
735 func (T2) String() string { return "Hello, world" }
736
737 var x string
738 var y T1
739 var z T2
740
741 we can simplify
742
743 fmt.Sprintf("%s", x)
744 fmt.Sprintf("%s", y)
745 fmt.Sprintf("%s", z)
746
747 to
748
749 x
750 string(y)
751 z.String()
752
753 Available since
754
755 2017.1
756
757
758 Default: off. Enable by setting `"analyses": {"S1025": true}`.
759
760 Package documentation: [S1025](https://staticcheck.dev/docs/checks/#S1025)
761
762 <a id='S1028'></a>
763 ## `S1028`: Simplify error construction with fmt.Errorf
764
765 Before:
766
767 errors.New(fmt.Sprintf(...))
768
769 After:
770
771 fmt.Errorf(...)
772
773 Available since
774
775 2017.1
776
777
778 Default: on.
779
780 Package documentation: [S1028](https://staticcheck.dev/docs/checks/#S1028)
781
782 <a id='S1029'></a>
783 ## `S1029`: Range over the string directly
784
785 Ranging over a string will yield byte offsets and runes. If the offset isn't used, this is functionally equivalent to converting the string to a slice of runes and ranging over that. Ranging directly over the string will be more performant, however, as it avoids allocating a new slice, the size of which depends on the length of the string.
786
787 Before:
788
789 for _, r := range []rune(s) {}
790
791 After:
792
793 for _, r := range s {}
794
795 Available since
796
797 2017.1
798
799
800 Default: off. Enable by setting `"analyses": {"S1029": true}`.
801
802 Package documentation: [S1029](https://staticcheck.dev/docs/checks/#S1029)
803
804 <a id='S1030'></a>
805 ## `S1030`: Use bytes.Buffer.String or bytes.Buffer.Bytes
806
807 bytes.Buffer has both a String and a Bytes method. It is almost never necessary to use string(buf.Bytes()) or \[]byte(buf.String()) – simply use the other method.
808
809 The only exception to this are map lookups. Due to a compiler optimization, m\[string(buf.Bytes())] is more efficient than m\[buf.String()].
810
811 Available since
812
813 2017.1
814
815
816 Default: on.
817
818 Package documentation: [S1030](https://staticcheck.dev/docs/checks/#S1030)
819
820 <a id='S1031'></a>
821 ## `S1031`: Omit redundant nil check around loop
822
823 You can use range on nil slices and maps, the loop will simply never execute. This makes an additional nil check around the loop unnecessary.
824
825 Before:
826
827 if s != nil {
828 for _, x := range s {
829 ...
830 }
831 }
832
833 After:
834
835 for _, x := range s {
836 ...
837 }
838
839 Available since
840
841 2017.1
842
843
844 Default: on.
845
846 Package documentation: [S1031](https://staticcheck.dev/docs/checks/#S1031)
847
848 <a id='S1032'></a>
849 ## `S1032`: Use sort.Ints(x), sort.Float64s(x), and sort.Strings(x)
850
851 The sort.Ints, sort.Float64s and sort.Strings functions are easier to read than sort.Sort(sort.IntSlice(x)), sort.Sort(sort.Float64Slice(x)) and sort.Sort(sort.StringSlice(x)).
852
853 Before:
854
855 sort.Sort(sort.StringSlice(x))
856
857 After:
858
859 sort.Strings(x)
860
861 Available since
862
863 2019.1
864
865
866 Default: on.
867
868 Package documentation: [S1032](https://staticcheck.dev/docs/checks/#S1032)
869
870 <a id='S1033'></a>
871 ## `S1033`: Unnecessary guard around call to 'delete'
872
873 Calling delete on a nil map is a no-op.
874
875 Available since
876
877 2019.2
878
879
880 Default: on.
881
882 Package documentation: [S1033](https://staticcheck.dev/docs/checks/#S1033)
883
884 <a id='S1034'></a>
885 ## `S1034`: Use result of type assertion to simplify cases
886
887 Available since
888
889 2019.2
890
891
892 Default: on.
893
894 Package documentation: [S1034](https://staticcheck.dev/docs/checks/#S1034)
895
896 <a id='S1035'></a>
897 ## `S1035`: Redundant call to net/http.CanonicalHeaderKey in method call on net/http.Header
898
899 The methods on net/http.Header, namely Add, Del, Get and Set, already canonicalize the given header name.
900
901 Available since
902
903 2020.1
904
905
906 Default: on.
907
908 Package documentation: [S1035](https://staticcheck.dev/docs/checks/#S1035)
909
910 <a id='S1036'></a>
911 ## `S1036`: Unnecessary guard around map access
912
913 When accessing a map key that doesn't exist yet, one receives a zero value. Often, the zero value is a suitable value, for example when using append or doing integer math.
914
915 The following
916
917 if _, ok := m["foo"]; ok {
918 m["foo"] = append(m["foo"], "bar")
919 } else {
920 m["foo"] = []string{"bar"}
921 }
922
923 can be simplified to
924
925 m["foo"] = append(m["foo"], "bar")
926
927 and
928
929 if _, ok := m2["k"]; ok {
930 m2["k"] += 4
931 } else {
932 m2["k"] = 4
933 }
934
935 can be simplified to
936
937 m["k"] += 4
938
939 Available since
940
941 2020.1
942
943
944 Default: on.
945
946 Package documentation: [S1036](https://staticcheck.dev/docs/checks/#S1036)
947
948 <a id='S1037'></a>
949 ## `S1037`: Elaborate way of sleeping
950
951 Using a select statement with a single case receiving from the result of time.After is a very elaborate way of sleeping that can much simpler be expressed with a simple call to time.Sleep.
952
953 Available since
954
955 2020.1
956
957
958 Default: on.
959
960 Package documentation: [S1037](https://staticcheck.dev/docs/checks/#S1037)
961
962 <a id='S1038'></a>
963 ## `S1038`: Unnecessarily complex way of printing formatted string
964
965 Instead of using fmt.Print(fmt.Sprintf(...)), one can use fmt.Printf(...).
966
967 Available since
968
969 2020.1
970
971
972 Default: on.
973
974 Package documentation: [S1038](https://staticcheck.dev/docs/checks/#S1038)
975
976 <a id='S1039'></a>
977 ## `S1039`: Unnecessary use of fmt.Sprint
978
979 Calling fmt.Sprint with a single string argument is unnecessary and identical to using the string directly.
980
981 Available since
982
983 2020.1
984
985
986 Default: on.
987
988 Package documentation: [S1039](https://staticcheck.dev/docs/checks/#S1039)
989
990 <a id='S1040'></a>
991 ## `S1040`: Type assertion to current type
992
993 The type assertion x.(SomeInterface), when x already has type SomeInterface, can only fail if x is nil. Usually, this is left-over code from when x had a different type and you can safely delete the type assertion. If you want to check that x is not nil, consider being explicit and using an actual if x == nil comparison instead of relying on the type assertion panicking.
994
995 Available since
996
997 2021.1
998
999
1000 Default: on.
1001
1002 Package documentation: [S1040](https://staticcheck.dev/docs/checks/#S1040)
1003
1004 <a id='SA1000'></a>
1005 ## `SA1000`: Invalid regular expression
1006
1007 Available since
1008
1009 2017.1
1010
1011
1012 Default: off. Enable by setting `"analyses": {"SA1000": true}`.
1013
1014 Package documentation: [SA1000](https://staticcheck.dev/docs/checks/#SA1000)
1015
1016 <a id='SA1001'></a>
1017 ## `SA1001`: Invalid template
1018
1019 Available since
1020
1021 2017.1
1022
1023
1024 Default: on.
1025
1026 Package documentation: [SA1001](https://staticcheck.dev/docs/checks/#SA1001)
1027
1028 <a id='SA1002'></a>
1029 ## `SA1002`: Invalid format in time.Parse
1030
1031 Available since
1032
1033 2017.1
1034
1035
1036 Default: off. Enable by setting `"analyses": {"SA1002": true}`.
1037
1038 Package documentation: [SA1002](https://staticcheck.dev/docs/checks/#SA1002)
1039
1040 <a id='SA1003'></a>
1041 ## `SA1003`: Unsupported argument to functions in encoding/binary
1042
1043 The encoding/binary package can only serialize types with known sizes. This precludes the use of the int and uint types, as their sizes differ on different architectures. Furthermore, it doesn't support serializing maps, channels, strings, or functions.
1044
1045 Before Go 1.8, bool wasn't supported, either.
1046
1047 Available since
1048
1049 2017.1
1050
1051
1052 Default: off. Enable by setting `"analyses": {"SA1003": true}`.
1053
1054 Package documentation: [SA1003](https://staticcheck.dev/docs/checks/#SA1003)
1055
1056 <a id='SA1004'></a>
1057 ## `SA1004`: Suspiciously small untyped constant in time.Sleep
1058
1059 The time.Sleep function takes a time.Duration as its only argument. Durations are expressed in nanoseconds. Thus, calling time.Sleep(1) will sleep for 1 nanosecond. This is a common source of bugs, as sleep functions in other languages often accept seconds or milliseconds.
1060
1061 The time package provides constants such as time.Second to express large durations. These can be combined with arithmetic to express arbitrary durations, for example 5 \* time.Second for 5 seconds.
1062
1063 If you truly meant to sleep for a tiny amount of time, use n \* time.Nanosecond to signal to Staticcheck that you did mean to sleep for some amount of nanoseconds.
1064
1065 Available since
1066
1067 2017.1
1068
1069
1070 Default: on.
1071
1072 Package documentation: [SA1004](https://staticcheck.dev/docs/checks/#SA1004)
1073
1074 <a id='SA1005'></a>
1075 ## `SA1005`: Invalid first argument to exec.Command
1076
1077 os/exec runs programs directly (using variants of the fork and exec system calls on Unix systems). This shouldn't be confused with running a command in a shell. The shell will allow for features such as input redirection, pipes, and general scripting. The shell is also responsible for splitting the user's input into a program name and its arguments. For example, the equivalent to
1078
1079 ls / /tmp
1080
1081 would be
1082
1083 exec.Command("ls", "/", "/tmp")
1084
1085 If you want to run a command in a shell, consider using something like the following – but be aware that not all systems, particularly Windows, will have a /bin/sh program:
1086
1087 exec.Command("/bin/sh", "-c", "ls | grep Awesome")
1088
1089 Available since
1090
1091 2017.1
1092
1093
1094 Default: on.
1095
1096 Package documentation: [SA1005](https://staticcheck.dev/docs/checks/#SA1005)
1097
1098 <a id='SA1007'></a>
1099 ## `SA1007`: Invalid URL in net/url.Parse
1100
1101 Available since
1102
1103 2017.1
1104
1105
1106 Default: off. Enable by setting `"analyses": {"SA1007": true}`.
1107
1108 Package documentation: [SA1007](https://staticcheck.dev/docs/checks/#SA1007)
1109
1110 <a id='SA1008'></a>
1111 ## `SA1008`: Non-canonical key in http.Header map
1112
1113 Keys in http.Header maps are canonical, meaning they follow a specific combination of uppercase and lowercase letters. Methods such as http.Header.Add and http.Header.Del convert inputs into this canonical form before manipulating the map.
1114
1115 When manipulating http.Header maps directly, as opposed to using the provided methods, care should be taken to stick to canonical form in order to avoid inconsistencies. The following piece of code demonstrates one such inconsistency:
1116
1117 h := http.Header{}
1118 h["etag"] = []string{"1234"}
1119 h.Add("etag", "5678")
1120 fmt.Println(h)
1121
1122 // Output:
1123 // map[Etag:[5678] etag:[1234]]
1124
1125 The easiest way of obtaining the canonical form of a key is to use http.CanonicalHeaderKey.
1126
1127 Available since
1128
1129 2017.1
1130
1131
1132 Default: on.
1133
1134 Package documentation: [SA1008](https://staticcheck.dev/docs/checks/#SA1008)
1135
1136 <a id='SA1010'></a>
1137 ## `SA1010`: (*regexp.Regexp).FindAll called with n == 0, which will always return zero results
1138
1139 If n >= 0, the function returns at most n matches/submatches. To return all results, specify a negative number.
1140
1141 Available since
1142
1143 2017.1
1144
1145
1146 Default: off. Enable by setting `"analyses": {"SA1010": true}`.
1147
1148 Package documentation: [SA1010](https://staticcheck.dev/docs/checks/#SA1010)
1149
1150 <a id='SA1011'></a>
1151 ## `SA1011`: Various methods in the 'strings' package expect valid UTF-8, but invalid input is provided
1152
1153 Available since
1154
1155 2017.1
1156
1157
1158 Default: off. Enable by setting `"analyses": {"SA1011": true}`.
1159
1160 Package documentation: [SA1011](https://staticcheck.dev/docs/checks/#SA1011)
1161
1162 <a id='SA1012'></a>
1163 ## `SA1012`: A nil context.Context is being passed to a function, consider using context.TODO instead
1164
1165 Available since
1166
1167 2017.1
1168
1169
1170 Default: on.
1171
1172 Package documentation: [SA1012](https://staticcheck.dev/docs/checks/#SA1012)
1173
1174 <a id='SA1013'></a>
1175 ## `SA1013`: io.Seeker.Seek is being called with the whence constant as the first argument, but it should be the second
1176
1177 Available since
1178
1179 2017.1
1180
1181
1182 Default: on.
1183
1184 Package documentation: [SA1013](https://staticcheck.dev/docs/checks/#SA1013)
1185
1186 <a id='SA1014'></a>
1187 ## `SA1014`: Non-pointer value passed to Unmarshal or Decode
1188
1189 Available since
1190
1191 2017.1
1192
1193
1194 Default: off. Enable by setting `"analyses": {"SA1014": true}`.
1195
1196 Package documentation: [SA1014](https://staticcheck.dev/docs/checks/#SA1014)
1197
1198 <a id='SA1015'></a>
1199 ## `SA1015`: Using time.Tick in a way that will leak. Consider using time.NewTicker, and only use time.Tick in tests, commands and endless functions
1200
1201 Before Go 1.23, time.Tickers had to be closed to be able to be garbage collected. Since time.Tick doesn't make it possible to close the underlying ticker, using it repeatedly would leak memory.
1202
1203 Go 1.23 fixes this by allowing tickers to be collected even if they weren't closed.
1204
1205 Available since
1206
1207 2017.1
1208
1209
1210 Default: off. Enable by setting `"analyses": {"SA1015": true}`.
1211
1212 Package documentation: [SA1015](https://staticcheck.dev/docs/checks/#SA1015)
1213
1214 <a id='SA1016'></a>
1215 ## `SA1016`: Trapping a signal that cannot be trapped
1216
1217 Not all signals can be intercepted by a process. Specifically, on UNIX-like systems, the syscall.SIGKILL and syscall.SIGSTOP signals are never passed to the process, but instead handled directly by the kernel. It is therefore pointless to try and handle these signals.
1218
1219 Available since
1220
1221 2017.1
1222
1223
1224 Default: on.
1225
1226 Package documentation: [SA1016](https://staticcheck.dev/docs/checks/#SA1016)
1227
1228 <a id='SA1017'></a>
1229 ## `SA1017`: Channels used with os/signal.Notify should be buffered
1230
1231 The os/signal package uses non-blocking channel sends when delivering signals. If the receiving end of the channel isn't ready and the channel is either unbuffered or full, the signal will be dropped. To avoid missing signals, the channel should be buffered and of the appropriate size. For a channel used for notification of just one signal value, a buffer of size 1 is sufficient.
1232
1233 Available since
1234
1235 2017.1
1236
1237
1238 Default: off. Enable by setting `"analyses": {"SA1017": true}`.
1239
1240 Package documentation: [SA1017](https://staticcheck.dev/docs/checks/#SA1017)
1241
1242 <a id='SA1018'></a>
1243 ## `SA1018`: strings.Replace called with n == 0, which does nothing
1244
1245 With n == 0, zero instances will be replaced. To replace all instances, use a negative number, or use strings.ReplaceAll.
1246
1247 Available since
1248
1249 2017.1
1250
1251
1252 Default: off. Enable by setting `"analyses": {"SA1018": true}`.
1253
1254 Package documentation: [SA1018](https://staticcheck.dev/docs/checks/#SA1018)
1255
1256 <a id='SA1020'></a>
1257 ## `SA1020`: Using an invalid host:port pair with a net.Listen-related function
1258
1259 Available since
1260
1261 2017.1
1262
1263
1264 Default: off. Enable by setting `"analyses": {"SA1020": true}`.
1265
1266 Package documentation: [SA1020](https://staticcheck.dev/docs/checks/#SA1020)
1267
1268 <a id='SA1021'></a>
1269 ## `SA1021`: Using bytes.Equal to compare two net.IP
1270
1271 A net.IP stores an IPv4 or IPv6 address as a slice of bytes. The length of the slice for an IPv4 address, however, can be either 4 or 16 bytes long, using different ways of representing IPv4 addresses. In order to correctly compare two net.IPs, the net.IP.Equal method should be used, as it takes both representations into account.
1272
1273 Available since
1274
1275 2017.1
1276
1277
1278 Default: off. Enable by setting `"analyses": {"SA1021": true}`.
1279
1280 Package documentation: [SA1021](https://staticcheck.dev/docs/checks/#SA1021)
1281
1282 <a id='SA1023'></a>
1283 ## `SA1023`: Modifying the buffer in an io.Writer implementation
1284
1285 Write must not modify the slice data, even temporarily.
1286
1287 Available since
1288
1289 2017.1
1290
1291
1292 Default: off. Enable by setting `"analyses": {"SA1023": true}`.
1293
1294 Package documentation: [SA1023](https://staticcheck.dev/docs/checks/#SA1023)
1295
1296 <a id='SA1024'></a>
1297 ## `SA1024`: A string cutset contains duplicate characters
1298
1299 The strings.TrimLeft and strings.TrimRight functions take cutsets, not prefixes. A cutset is treated as a set of characters to remove from a string. For example,
1300
1301 strings.TrimLeft("42133word", "1234")
1302
1303 will result in the string "word" – any characters that are 1, 2, 3 or 4 are cut from the left of the string.
1304
1305 In order to remove one string from another, use strings.TrimPrefix instead.
1306
1307 Available since
1308
1309 2017.1
1310
1311
1312 Default: off. Enable by setting `"analyses": {"SA1024": true}`.
1313
1314 Package documentation: [SA1024](https://staticcheck.dev/docs/checks/#SA1024)
1315
1316 <a id='SA1025'></a>
1317 ## `SA1025`: It is not possible to use (*time.Timer).Reset's return value correctly
1318
1319 Available since
1320
1321 2019.1
1322
1323
1324 Default: off. Enable by setting `"analyses": {"SA1025": true}`.
1325
1326 Package documentation: [SA1025](https://staticcheck.dev/docs/checks/#SA1025)
1327
1328 <a id='SA1026'></a>
1329 ## `SA1026`: Cannot marshal channels or functions
1330
1331 Available since
1332
1333 2019.2
1334
1335
1336 Default: off. Enable by setting `"analyses": {"SA1026": true}`.
1337
1338 Package documentation: [SA1026](https://staticcheck.dev/docs/checks/#SA1026)
1339
1340 <a id='SA1027'></a>
1341 ## `SA1027`: Atomic access to 64-bit variable must be 64-bit aligned
1342
1343 On ARM, x86-32, and 32-bit MIPS, it is the caller's responsibility to arrange for 64-bit alignment of 64-bit words accessed atomically. The first word in a variable or in an allocated struct, array, or slice can be relied upon to be 64-bit aligned.
1344
1345 You can use the structlayout tool to inspect the alignment of fields in a struct.
1346
1347 Available since
1348
1349 2019.2
1350
1351
1352 Default: off. Enable by setting `"analyses": {"SA1027": true}`.
1353
1354 Package documentation: [SA1027](https://staticcheck.dev/docs/checks/#SA1027)
1355
1356 <a id='SA1028'></a>
1357 ## `SA1028`: sort.Slice can only be used on slices
1358
1359 The first argument of sort.Slice must be a slice.
1360
1361 Available since
1362
1363 2020.1
1364
1365
1366 Default: off. Enable by setting `"analyses": {"SA1028": true}`.
1367
1368 Package documentation: [SA1028](https://staticcheck.dev/docs/checks/#SA1028)
1369
1370 <a id='SA1029'></a>
1371 ## `SA1029`: Inappropriate key in call to context.WithValue
1372
1373 The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of WithValue should define their own types for keys.
1374
1375 To avoid allocating when assigning to an interface{}, context keys often have concrete type struct{}. Alternatively, exported context key variables' static type should be a pointer or interface.
1376
1377 Available since
1378
1379 2020.1
1380
1381
1382 Default: off. Enable by setting `"analyses": {"SA1029": true}`.
1383
1384 Package documentation: [SA1029](https://staticcheck.dev/docs/checks/#SA1029)
1385
1386 <a id='SA1030'></a>
1387 ## `SA1030`: Invalid argument in call to a strconv function
1388
1389 This check validates the format, number base and bit size arguments of the various parsing and formatting functions in strconv.
1390
1391 Available since
1392
1393 2021.1
1394
1395
1396 Default: off. Enable by setting `"analyses": {"SA1030": true}`.
1397
1398 Package documentation: [SA1030](https://staticcheck.dev/docs/checks/#SA1030)
1399
1400 <a id='SA1031'></a>
1401 ## `SA1031`: Overlapping byte slices passed to an encoder
1402
1403 In an encoding function of the form Encode(dst, src), dst and src were found to reference the same memory. This can result in src bytes being overwritten before they are read, when the encoder writes more than one byte per src byte.
1404
1405 Available since
1406
1407 2024.1
1408
1409
1410 Default: off. Enable by setting `"analyses": {"SA1031": true}`.
1411
1412 Package documentation: [SA1031](https://staticcheck.dev/docs/checks/#SA1031)
1413
1414 <a id='SA1032'></a>
1415 ## `SA1032`: Wrong order of arguments to errors.Is
1416
1417 The first argument of the function errors.Is is the error that we have and the second argument is the error we're trying to match against. For example:
1418
1419 if errors.Is(err, io.EOF) { ... }
1420
1421 This check detects some cases where the two arguments have been swapped. It flags any calls where the first argument is referring to a package-level error variable, such as
1422
1423 if errors.Is(io.EOF, err) { /* this is wrong */ }
1424
1425 Available since
1426
1427 2024.1
1428
1429
1430 Default: off. Enable by setting `"analyses": {"SA1032": true}`.
1431
1432 Package documentation: [SA1032](https://staticcheck.dev/docs/checks/#SA1032)
1433
1434 <a id='SA2001'></a>
1435 ## `SA2001`: Empty critical section, did you mean to defer the unlock?
1436
1437 Empty critical sections of the kind
1438
1439 mu.Lock()
1440 mu.Unlock()
1441
1442 are very often a typo, and the following was intended instead:
1443
1444 mu.Lock()
1445 defer mu.Unlock()
1446
1447 Do note that sometimes empty critical sections can be useful, as a form of signaling to wait on another goroutine. Many times, there are simpler ways of achieving the same effect. When that isn't the case, the code should be amply commented to avoid confusion. Combining such comments with a //lint:ignore directive can be used to suppress this rare false positive.
1448
1449 Available since
1450
1451 2017.1
1452
1453
1454 Default: on.
1455
1456 Package documentation: [SA2001](https://staticcheck.dev/docs/checks/#SA2001)
1457
1458 <a id='SA2002'></a>
1459 ## `SA2002`: Called testing.T.FailNow or SkipNow in a goroutine, which isn't allowed
1460
1461 Available since
1462
1463 2017.1
1464
1465
1466 Default: off. Enable by setting `"analyses": {"SA2002": true}`.
1467
1468 Package documentation: [SA2002](https://staticcheck.dev/docs/checks/#SA2002)
1469
1470 <a id='SA2003'></a>
1471 ## `SA2003`: Deferred Lock right after locking, likely meant to defer Unlock instead
1472
1473 Available since
1474
1475 2017.1
1476
1477
1478 Default: off. Enable by setting `"analyses": {"SA2003": true}`.
1479
1480 Package documentation: [SA2003](https://staticcheck.dev/docs/checks/#SA2003)
1481
1482 <a id='SA3000'></a>
1483 ## `SA3000`: TestMain doesn't call os.Exit, hiding test failures
1484
1485 Test executables (and in turn 'go test') exit with a non-zero status code if any tests failed. When specifying your own TestMain function, it is your responsibility to arrange for this, by calling os.Exit with the correct code. The correct code is returned by (\*testing.M).Run, so the usual way of implementing TestMain is to end it with os.Exit(m.Run()).
1486
1487 Available since
1488
1489 2017.1
1490
1491
1492 Default: on.
1493
1494 Package documentation: [SA3000](https://staticcheck.dev/docs/checks/#SA3000)
1495
1496 <a id='SA3001'></a>
1497 ## `SA3001`: Assigning to b.N in benchmarks distorts the results
1498
1499 The testing package dynamically sets b.N to improve the reliability of benchmarks and uses it in computations to determine the duration of a single operation. Benchmark code must not alter b.N as this would falsify results.
1500
1501 Available since
1502
1503 2017.1
1504
1505
1506 Default: on.
1507
1508 Package documentation: [SA3001](https://staticcheck.dev/docs/checks/#SA3001)
1509
1510 <a id='SA4000'></a>
1511 ## `SA4000`: Binary operator has identical expressions on both sides
1512
1513 Available since
1514
1515 2017.1
1516
1517
1518 Default: on.
1519
1520 Package documentation: [SA4000](https://staticcheck.dev/docs/checks/#SA4000)
1521
1522 <a id='SA4001'></a>
1523 ## `SA4001`: &*x gets simplified to x, it does not copy x
1524
1525 Available since
1526
1527 2017.1
1528
1529
1530 Default: on.
1531
1532 Package documentation: [SA4001](https://staticcheck.dev/docs/checks/#SA4001)
1533
1534 <a id='SA4003'></a>
1535 ## `SA4003`: Comparing unsigned values against negative values is pointless
1536
1537 Available since
1538
1539 2017.1
1540
1541
1542 Default: on.
1543
1544 Package documentation: [SA4003](https://staticcheck.dev/docs/checks/#SA4003)
1545
1546 <a id='SA4004'></a>
1547 ## `SA4004`: The loop exits unconditionally after one iteration
1548
1549 Available since
1550
1551 2017.1
1552
1553
1554 Default: on.
1555
1556 Package documentation: [SA4004](https://staticcheck.dev/docs/checks/#SA4004)
1557
1558 <a id='SA4005'></a>
1559 ## `SA4005`: Field assignment that will never be observed. Did you mean to use a pointer receiver?
1560
1561 Available since
1562
1563 2021.1
1564
1565
1566 Default: off. Enable by setting `"analyses": {"SA4005": true}`.
1567
1568 Package documentation: [SA4005](https://staticcheck.dev/docs/checks/#SA4005)
1569
1570 <a id='SA4006'></a>
1571 ## `SA4006`: A value assigned to a variable is never read before being overwritten. Forgotten error check or dead code?
1572
1573 Available since
1574
1575 2017.1
1576
1577
1578 Default: off. Enable by setting `"analyses": {"SA4006": true}`.
1579
1580 Package documentation: [SA4006](https://staticcheck.dev/docs/checks/#SA4006)
1581
1582 <a id='SA4008'></a>
1583 ## `SA4008`: The variable in the loop condition never changes, are you incrementing the wrong variable?
1584
1585 For example:
1586
1587 for i := 0; i < 10; j++ { ... }
1588
1589 This may also occur when a loop can only execute once because of unconditional control flow that terminates the loop. For example, when a loop body contains an unconditional break, return, or panic:
1590
1591 func f() {
1592 panic("oops")
1593 }
1594 func g() {
1595 for i := 0; i < 10; i++ {
1596 // f unconditionally calls panic, which means "i" is
1597 // never incremented.
1598 f()
1599 }
1600 }
1601
1602 Available since
1603
1604 2017.1
1605
1606
1607 Default: off. Enable by setting `"analyses": {"SA4008": true}`.
1608
1609 Package documentation: [SA4008](https://staticcheck.dev/docs/checks/#SA4008)
1610
1611 <a id='SA4009'></a>
1612 ## `SA4009`: A function argument is overwritten before its first use
1613
1614 Available since
1615
1616 2017.1
1617
1618
1619 Default: off. Enable by setting `"analyses": {"SA4009": true}`.
1620
1621 Package documentation: [SA4009](https://staticcheck.dev/docs/checks/#SA4009)
1622
1623 <a id='SA4010'></a>
1624 ## `SA4010`: The result of append will never be observed anywhere
1625
1626 Available since
1627
1628 2017.1
1629
1630
1631 Default: off. Enable by setting `"analyses": {"SA4010": true}`.
1632
1633 Package documentation: [SA4010](https://staticcheck.dev/docs/checks/#SA4010)
1634
1635 <a id='SA4011'></a>
1636 ## `SA4011`: Break statement with no effect. Did you mean to break out of an outer loop?
1637
1638 Available since
1639
1640 2017.1
1641
1642
1643 Default: on.
1644
1645 Package documentation: [SA4011](https://staticcheck.dev/docs/checks/#SA4011)
1646
1647 <a id='SA4012'></a>
1648 ## `SA4012`: Comparing a value against NaN even though no value is equal to NaN
1649
1650 Available since
1651
1652 2017.1
1653
1654
1655 Default: off. Enable by setting `"analyses": {"SA4012": true}`.
1656
1657 Package documentation: [SA4012](https://staticcheck.dev/docs/checks/#SA4012)
1658
1659 <a id='SA4013'></a>
1660 ## `SA4013`: Negating a boolean twice (!!b) is the same as writing b. This is either redundant, or a typo.
1661
1662 Available since
1663
1664 2017.1
1665
1666
1667 Default: on.
1668
1669 Package documentation: [SA4013](https://staticcheck.dev/docs/checks/#SA4013)
1670
1671 <a id='SA4014'></a>
1672 ## `SA4014`: 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
1673
1674 Available since
1675
1676 2017.1
1677
1678
1679 Default: on.
1680
1681 Package documentation: [SA4014](https://staticcheck.dev/docs/checks/#SA4014)
1682
1683 <a id='SA4015'></a>
1684 ## `SA4015`: Calling functions like math.Ceil on floats converted from integers doesn't do anything useful
1685
1686 Available since
1687
1688 2017.1
1689
1690
1691 Default: off. Enable by setting `"analyses": {"SA4015": true}`.
1692
1693 Package documentation: [SA4015](https://staticcheck.dev/docs/checks/#SA4015)
1694
1695 <a id='SA4016'></a>
1696 ## `SA4016`: Certain bitwise operations, such as x ^ 0, do not do anything useful
1697
1698 Available since
1699
1700 2017.1
1701
1702
1703 Default: on.
1704
1705 Package documentation: [SA4016](https://staticcheck.dev/docs/checks/#SA4016)
1706
1707 <a id='SA4017'></a>
1708 ## `SA4017`: Discarding the return values of a function without side effects, making the call pointless
1709
1710 Available since
1711
1712 2017.1
1713
1714
1715 Default: off. Enable by setting `"analyses": {"SA4017": true}`.
1716
1717 Package documentation: [SA4017](https://staticcheck.dev/docs/checks/#SA4017)
1718
1719 <a id='SA4018'></a>
1720 ## `SA4018`: Self-assignment of variables
1721
1722 Available since
1723
1724 2017.1
1725
1726
1727 Default: off. Enable by setting `"analyses": {"SA4018": true}`.
1728
1729 Package documentation: [SA4018](https://staticcheck.dev/docs/checks/#SA4018)
1730
1731 <a id='SA4019'></a>
1732 ## `SA4019`: Multiple, identical build constraints in the same file
1733
1734 Available since
1735
1736 2017.1
1737
1738
1739 Default: on.
1740
1741 Package documentation: [SA4019](https://staticcheck.dev/docs/checks/#SA4019)
1742
1743 <a id='SA4020'></a>
1744 ## `SA4020`: Unreachable case clause in a type switch
1745
1746 In a type switch like the following
1747
1748 type T struct{}
1749 func (T) Read(b []byte) (int, error) { return 0, nil }
1750
1751 var v any = T{}
1752
1753 switch v.(type) {
1754 case io.Reader:
1755 // ...
1756 case T:
1757 // unreachable
1758 }
1759
1760 the second case clause can never be reached because T implements io.Reader and case clauses are evaluated in source order.
1761
1762 Another example:
1763
1764 type T struct{}
1765 func (T) Read(b []byte) (int, error) { return 0, nil }
1766 func (T) Close() error { return nil }
1767
1768 var v any = T{}
1769
1770 switch v.(type) {
1771 case io.Reader:
1772 // ...
1773 case io.ReadCloser:
1774 // unreachable
1775 }
1776
1777 Even though T has a Close method and thus implements io.ReadCloser, io.Reader will always match first. The method set of io.Reader is a subset of io.ReadCloser. Thus it is impossible to match the second case without matching the first case.
1778
1779 ### Structurally equivalent interfaces {#hdr-Structurally_equivalent_interfaces}
1780
1781 A special case of the previous example are structurally identical interfaces. Given these declarations
1782
1783 type T error
1784 type V error
1785
1786 func doSomething() error {
1787 err, ok := doAnotherThing()
1788 if ok {
1789 return T(err)
1790 }
1791
1792 return U(err)
1793 }
1794
1795 the following type switch will have an unreachable case clause:
1796
1797 switch doSomething().(type) {
1798 case T:
1799 // ...
1800 case V:
1801 // unreachable
1802 }
1803
1804 T will always match before V because they are structurally equivalent and therefore doSomething()'s return value implements both.
1805
1806 Available since
1807
1808 2019.2
1809
1810
1811 Default: on.
1812
1813 Package documentation: [SA4020](https://staticcheck.dev/docs/checks/#SA4020)
1814
1815 <a id='SA4022'></a>
1816 ## `SA4022`: Comparing the address of a variable against nil
1817
1818 Code such as 'if &x == nil' is meaningless, because taking the address of a variable always yields a non-nil pointer.
1819
1820 Available since
1821
1822 2020.1
1823
1824
1825 Default: on.
1826
1827 Package documentation: [SA4022](https://staticcheck.dev/docs/checks/#SA4022)
1828
1829 <a id='SA4023'></a>
1830 ## `SA4023`: Impossible comparison of interface value with untyped nil
1831
1832 Under the covers, interfaces are implemented as two elements, a type T and a value V. V is a concrete value such as an int, struct or pointer, never an interface itself, and has type T. For instance, if we store the int value 3 in an interface, the resulting interface value has, schematically, (T=int, V=3). The value V is also known as the interface's dynamic value, since a given interface variable might hold different values V (and corresponding types T) during the execution of the program.
1833
1834 An interface value is nil only if the V and T are both unset, (T=nil, V is not set), In particular, a nil interface will always hold a nil type. If we store a nil pointer of type \*int inside an interface value, the inner type will be \*int regardless of the value of the pointer: (T=\*int, V=nil). Such an interface value will therefore be non-nil even when the pointer value V inside is nil.
1835
1836 This situation can be confusing, and arises when a nil value is stored inside an interface value such as an error return:
1837
1838 func returnsError() error {
1839 var p *MyError = nil
1840 if bad() {
1841 p = ErrBad
1842 }
1843 return p // Will always return a non-nil error.
1844 }
1845
1846 If all goes well, the function returns a nil p, so the return value is an error interface value holding (T=\*MyError, V=nil). This means that if the caller compares the returned error to nil, it will always look as if there was an error even if nothing bad happened. To return a proper nil error to the caller, the function must return an explicit nil:
1847
1848 func returnsError() error {
1849 if bad() {
1850 return ErrBad
1851 }
1852 return nil
1853 }
1854
1855 It's a good idea for functions that return errors always to use the error type in their signature (as we did above) rather than a concrete type such as \*MyError, to help guarantee the error is created correctly. As an example, os.Open returns an error even though, if not nil, it's always of concrete type \*os.PathError.
1856
1857 Similar situations to those described here can arise whenever interfaces are used. Just keep in mind that if any concrete value has been stored in the interface, the interface will not be nil. For more information, see The Laws of Reflection at [https://golang.org/doc/articles/laws\_of\_reflection.html](https://golang.org/doc/articles/laws_of_reflection.html).
1858
1859 This text has been copied from [https://golang.org/doc/faq#nil\_error](https://golang.org/doc/faq#nil_error), licensed under the Creative Commons Attribution 3.0 License.
1860
1861 Available since
1862
1863 2020.2
1864
1865
1866 Default: off. Enable by setting `"analyses": {"SA4023": true}`.
1867
1868 Package documentation: [SA4023](https://staticcheck.dev/docs/checks/#SA4023)
1869
1870 <a id='SA4024'></a>
1871 ## `SA4024`: Checking for impossible return value from a builtin function
1872
1873 Return values of the len and cap builtins cannot be negative.
1874
1875 See [https://golang.org/pkg/builtin/#len](https://golang.org/pkg/builtin/#len) and [https://golang.org/pkg/builtin/#cap](https://golang.org/pkg/builtin/#cap).
1876
1877 Example:
1878
1879 if len(slice) < 0 {
1880 fmt.Println("unreachable code")
1881 }
1882
1883 Available since
1884
1885 2021.1
1886
1887
1888 Default: on.
1889
1890 Package documentation: [SA4024](https://staticcheck.dev/docs/checks/#SA4024)
1891
1892 <a id='SA4025'></a>
1893 ## `SA4025`: Integer division of literals that results in zero
1894
1895 When dividing two integer constants, the result will also be an integer. Thus, a division such as 2 / 3 results in 0. This is true for all of the following examples:
1896
1897 _ = 2 / 3
1898 const _ = 2 / 3
1899 const _ float64 = 2 / 3
1900 _ = float64(2 / 3)
1901
1902 Staticcheck will flag such divisions if both sides of the division are integer literals, as it is highly unlikely that the division was intended to truncate to zero. Staticcheck will not flag integer division involving named constants, to avoid noisy positives.
1903
1904 Available since
1905
1906 2021.1
1907
1908
1909 Default: on.
1910
1911 Package documentation: [SA4025](https://staticcheck.dev/docs/checks/#SA4025)
1912
1913 <a id='SA4026'></a>
1914 ## `SA4026`: Go constants cannot express negative zero
1915
1916 In IEEE 754 floating point math, zero has a sign and can be positive or negative. This can be useful in certain numerical code.
1917
1918 Go constants, however, cannot express negative zero. This means that the literals -0.0 and 0.0 have the same ideal value (zero) and will both represent positive zero at runtime.
1919
1920 To explicitly and reliably create a negative zero, you can use the math.Copysign function: math.Copysign(0, -1).
1921
1922 Available since
1923
1924 2021.1
1925
1926
1927 Default: on.
1928
1929 Package documentation: [SA4026](https://staticcheck.dev/docs/checks/#SA4026)
1930
1931 <a id='SA4027'></a>
1932 ## `SA4027`: (*net/url.URL).Query returns a copy, modifying it doesn't change the URL
1933
1934 (\*net/url.URL).Query parses the current value of net/url.URL.RawQuery and returns it as a map of type net/url.Values. Subsequent changes to this map will not affect the URL unless the map gets encoded and assigned to the URL's RawQuery.
1935
1936 As a consequence, the following code pattern is an expensive no-op: u.Query().Add(key, value).
1937
1938 Available since
1939
1940 2021.1
1941
1942
1943 Default: on.
1944
1945 Package documentation: [SA4027](https://staticcheck.dev/docs/checks/#SA4027)
1946
1947 <a id='SA4028'></a>
1948 ## `SA4028`: x % 1 is always zero
1949
1950 Available since
1951
1952 2022.1
1953
1954
1955 Default: on.
1956
1957 Package documentation: [SA4028](https://staticcheck.dev/docs/checks/#SA4028)
1958
1959 <a id='SA4029'></a>
1960 ## `SA4029`: Ineffective attempt at sorting slice
1961
1962 sort.Float64Slice, sort.IntSlice, and sort.StringSlice are types, not functions. Doing x = sort.StringSlice(x) does nothing, especially not sort any values. The correct usage is sort.Sort(sort.StringSlice(x)) or sort.StringSlice(x).Sort(), but there are more convenient helpers, namely sort.Float64s, sort.Ints, and sort.Strings.
1963
1964 Available since
1965
1966 2022.1
1967
1968
1969 Default: on.
1970
1971 Package documentation: [SA4029](https://staticcheck.dev/docs/checks/#SA4029)
1972
1973 <a id='SA4030'></a>
1974 ## `SA4030`: Ineffective attempt at generating random number
1975
1976 Functions in the math/rand package that accept upper limits, such as Intn, generate random numbers in the half-open interval \[0,n). In other words, the generated numbers will be >= 0 and \< n – they don't include n. rand.Intn(1) therefore doesn't generate 0 or 1, it always generates 0.
1977
1978 Available since
1979
1980 2022.1
1981
1982
1983 Default: on.
1984
1985 Package documentation: [SA4030](https://staticcheck.dev/docs/checks/#SA4030)
1986
1987 <a id='SA4031'></a>
1988 ## `SA4031`: Checking never-nil value against nil
1989
1990 Available since
1991
1992 2022.1
1993
1994
1995 Default: off. Enable by setting `"analyses": {"SA4031": true}`.
1996
1997 Package documentation: [SA4031](https://staticcheck.dev/docs/checks/#SA4031)
1998
1999 <a id='SA4032'></a>
2000 ## `SA4032`: Comparing runtime.GOOS or runtime.GOARCH against impossible value
2001
2002 Available since
2003
2004 2024.1
2005
2006
2007 Default: on.
2008
2009 Package documentation: [SA4032](https://staticcheck.dev/docs/checks/#SA4032)
2010
2011 <a id='SA5000'></a>
2012 ## `SA5000`: Assignment to nil map
2013
2014 Available since
2015
2016 2017.1
2017
2018
2019 Default: off. Enable by setting `"analyses": {"SA5000": true}`.
2020
2021 Package documentation: [SA5000](https://staticcheck.dev/docs/checks/#SA5000)
2022
2023 <a id='SA5001'></a>
2024 ## `SA5001`: Deferring Close before checking for a possible error
2025
2026 Available since
2027
2028 2017.1
2029
2030
2031 Default: on.
2032
2033 Package documentation: [SA5001](https://staticcheck.dev/docs/checks/#SA5001)
2034
2035 <a id='SA5002'></a>
2036 ## `SA5002`: The empty for loop ('for {}') spins and can block the scheduler
2037
2038 Available since
2039
2040 2017.1
2041
2042
2043 Default: off. Enable by setting `"analyses": {"SA5002": true}`.
2044
2045 Package documentation: [SA5002](https://staticcheck.dev/docs/checks/#SA5002)
2046
2047 <a id='SA5003'></a>
2048 ## `SA5003`: Defers in infinite loops will never execute
2049
2050 Defers are scoped to the surrounding function, not the surrounding block. In a function that never returns, i.e. one containing an infinite loop, defers will never execute.
2051
2052 Available since
2053
2054 2017.1
2055
2056
2057 Default: on.
2058
2059 Package documentation: [SA5003](https://staticcheck.dev/docs/checks/#SA5003)
2060
2061 <a id='SA5004'></a>
2062 ## `SA5004`: 'for { select { ...' with an empty default branch spins
2063
2064 Available since
2065
2066 2017.1
2067
2068
2069 Default: on.
2070
2071 Package documentation: [SA5004](https://staticcheck.dev/docs/checks/#SA5004)
2072
2073 <a id='SA5005'></a>
2074 ## `SA5005`: The finalizer references the finalized object, preventing garbage collection
2075
2076 A finalizer is a function associated with an object that runs when the garbage collector is ready to collect said object, that is when the object is no longer referenced by anything.
2077
2078 If the finalizer references the object, however, it will always remain as the final reference to that object, preventing the garbage collector from collecting the object. The finalizer will never run, and the object will never be collected, leading to a memory leak. That is why the finalizer should instead use its first argument to operate on the object. That way, the number of references can temporarily go to zero before the object is being passed to the finalizer.
2079
2080 Available since
2081
2082 2017.1
2083
2084
2085 Default: off. Enable by setting `"analyses": {"SA5005": true}`.
2086
2087 Package documentation: [SA5005](https://staticcheck.dev/docs/checks/#SA5005)
2088
2089 <a id='SA5007'></a>
2090 ## `SA5007`: Infinite recursive call
2091
2092 A function that calls itself recursively needs to have an exit condition. Otherwise it will recurse forever, until the system runs out of memory.
2093
2094 This issue can be caused by simple bugs such as forgetting to add an exit condition. It can also happen "on purpose". Some languages have tail call optimization which makes certain infinite recursive calls safe to use. Go, however, does not implement TCO, and as such a loop should be used instead.
2095
2096 Available since
2097
2098 2017.1
2099
2100
2101 Default: off. Enable by setting `"analyses": {"SA5007": true}`.
2102
2103 Package documentation: [SA5007](https://staticcheck.dev/docs/checks/#SA5007)
2104
2105 <a id='SA5008'></a>
2106 ## `SA5008`: Invalid struct tag
2107
2108 Available since
2109
2110 2019.2
2111
2112
2113 Default: on.
2114
2115 Package documentation: [SA5008](https://staticcheck.dev/docs/checks/#SA5008)
2116
2117 <a id='SA5010'></a>
2118 ## `SA5010`: Impossible type assertion
2119
2120 Some type assertions can be statically proven to be impossible. This is the case when the method sets of both arguments of the type assertion conflict with each other, for example by containing the same method with different signatures.
2121
2122 The Go compiler already applies this check when asserting from an interface value to a concrete type. If the concrete type misses methods from the interface, or if function signatures don't match, then the type assertion can never succeed.
2123
2124 This check applies the same logic when asserting from one interface to another. If both interface types contain the same method but with different signatures, then the type assertion can never succeed, either.
2125
2126 Available since
2127
2128 2020.1
2129
2130
2131 Default: off. Enable by setting `"analyses": {"SA5010": true}`.
2132
2133 Package documentation: [SA5010](https://staticcheck.dev/docs/checks/#SA5010)
2134
2135 <a id='SA5011'></a>
2136 ## `SA5011`: Possible nil pointer dereference
2137
2138 A pointer is being dereferenced unconditionally, while also being checked against nil in another place. This suggests that the pointer may be nil and dereferencing it may panic. This is commonly a result of improperly ordered code or missing return statements. Consider the following examples:
2139
2140 func fn(x *int) {
2141 fmt.Println(*x)
2142
2143 // This nil check is equally important for the previous dereference
2144 if x != nil {
2145 foo(*x)
2146 }
2147 }
2148
2149 func TestFoo(t *testing.T) {
2150 x := compute()
2151 if x == nil {
2152 t.Errorf("nil pointer received")
2153 }
2154
2155 // t.Errorf does not abort the test, so if x is nil, the next line will panic.
2156 foo(*x)
2157 }
2158
2159 Staticcheck tries to deduce which functions abort control flow. For example, it is aware that a function will not continue execution after a call to panic or log.Fatal. However, sometimes this detection fails, in particular in the presence of conditionals. Consider the following example:
2160
2161 func Log(msg string, level int) {
2162 fmt.Println(msg)
2163 if level == levelFatal {
2164 os.Exit(1)
2165 }
2166 }
2167
2168 func Fatal(msg string) {
2169 Log(msg, levelFatal)
2170 }
2171
2172 func fn(x *int) {
2173 if x == nil {
2174 Fatal("unexpected nil pointer")
2175 }
2176 fmt.Println(*x)
2177 }
2178
2179 Staticcheck will flag the dereference of x, even though it is perfectly safe. Staticcheck is not able to deduce that a call to Fatal will exit the program. For the time being, the easiest workaround is to modify the definition of Fatal like so:
2180
2181 func Fatal(msg string) {
2182 Log(msg, levelFatal)
2183 panic("unreachable")
2184 }
2185
2186 We also hard-code functions from common logging packages such as logrus. Please file an issue if we're missing support for a popular package.
2187
2188 Available since
2189
2190 2020.1
2191
2192
2193 Default: off. Enable by setting `"analyses": {"SA5011": true}`.
2194
2195 Package documentation: [SA5011](https://staticcheck.dev/docs/checks/#SA5011)
2196
2197 <a id='SA5012'></a>
2198 ## `SA5012`: Passing odd-sized slice to function expecting even size
2199
2200 Some functions that take slices as parameters expect the slices to have an even number of elements. Often, these functions treat elements in a slice as pairs. For example, strings.NewReplacer takes pairs of old and new strings, and calling it with an odd number of elements would be an error.
2201
2202 Available since
2203
2204 2020.2
2205
2206
2207 Default: off. Enable by setting `"analyses": {"SA5012": true}`.
2208
2209 Package documentation: [SA5012](https://staticcheck.dev/docs/checks/#SA5012)
2210
2211 <a id='SA6000'></a>
2212 ## `SA6000`: Using regexp.Match or related in a loop, should use regexp.Compile
2213
2214 Available since
2215
2216 2017.1
2217
2218
2219 Default: off. Enable by setting `"analyses": {"SA6000": true}`.
2220
2221 Package documentation: [SA6000](https://staticcheck.dev/docs/checks/#SA6000)
2222
2223 <a id='SA6001'></a>
2224 ## `SA6001`: Missing an optimization opportunity when indexing maps by byte slices
2225
2226 Map keys must be comparable, which precludes the use of byte slices. This usually leads to using string keys and converting byte slices to strings.
2227
2228 Normally, a conversion of a byte slice to a string needs to copy the data and causes allocations. The compiler, however, recognizes m\[string(b)] and uses the data of b directly, without copying it, because it knows that the data can't change during the map lookup. This leads to the counter-intuitive situation that
2229
2230 k := string(b)
2231 println(m[k])
2232 println(m[k])
2233
2234 will be less efficient than
2235
2236 println(m[string(b)])
2237 println(m[string(b)])
2238
2239 because the first version needs to copy and allocate, while the second one does not.
2240
2241 For some history on this optimization, check out commit f5f5a8b6209f84961687d993b93ea0d397f5d5bf in the Go repository.
2242
2243 Available since
2244
2245 2017.1
2246
2247
2248 Default: off. Enable by setting `"analyses": {"SA6001": true}`.
2249
2250 Package documentation: [SA6001](https://staticcheck.dev/docs/checks/#SA6001)
2251
2252 <a id='SA6002'></a>
2253 ## `SA6002`: Storing non-pointer values in sync.Pool allocates memory
2254
2255 A sync.Pool is used to avoid unnecessary allocations and reduce the amount of work the garbage collector has to do.
2256
2257 When passing a value that is not a pointer to a function that accepts an interface, the value needs to be placed on the heap, which means an additional allocation. Slices are a common thing to put in sync.Pools, and they're structs with 3 fields (length, capacity, and a pointer to an array). In order to avoid the extra allocation, one should store a pointer to the slice instead.
2258
2259 See the comments on [https://go-review.googlesource.com/c/go/+/24371](https://go-review.googlesource.com/c/go/+/24371) that discuss this problem.
2260
2261 Available since
2262
2263 2017.1
2264
2265
2266 Default: off. Enable by setting `"analyses": {"SA6002": true}`.
2267
2268 Package documentation: [SA6002](https://staticcheck.dev/docs/checks/#SA6002)
2269
2270 <a id='SA6003'></a>
2271 ## `SA6003`: Converting a string to a slice of runes before ranging over it
2272
2273 You may want to loop over the runes in a string. Instead of converting the string to a slice of runes and looping over that, you can loop over the string itself. That is,
2274
2275 for _, r := range s {}
2276
2277 and
2278
2279 for _, r := range []rune(s) {}
2280
2281 will yield the same values. The first version, however, will be faster and avoid unnecessary memory allocations.
2282
2283 Do note that if you are interested in the indices, ranging over a string and over a slice of runes will yield different indices. The first one yields byte offsets, while the second one yields indices in the slice of runes.
2284
2285 Available since
2286
2287 2017.1
2288
2289
2290 Default: off. Enable by setting `"analyses": {"SA6003": true}`.
2291
2292 Package documentation: [SA6003](https://staticcheck.dev/docs/checks/#SA6003)
2293
2294 <a id='SA6005'></a>
2295 ## `SA6005`: Inefficient string comparison with strings.ToLower or strings.ToUpper
2296
2297 Converting two strings to the same case and comparing them like so
2298
2299 if strings.ToLower(s1) == strings.ToLower(s2) {
2300 ...
2301 }
2302
2303 is significantly more expensive than comparing them with strings.EqualFold(s1, s2). This is due to memory usage as well as computational complexity.
2304
2305 strings.ToLower will have to allocate memory for the new strings, as well as convert both strings fully, even if they differ on the very first byte. strings.EqualFold, on the other hand, compares the strings one character at a time. It doesn't need to create two intermediate strings and can return as soon as the first non-matching character has been found.
2306
2307 For a more in-depth explanation of this issue, see [https://blog.digitalocean.com/how-to-efficiently-compare-strings-in-go/](https://blog.digitalocean.com/how-to-efficiently-compare-strings-in-go/)
2308
2309 Available since
2310
2311 2019.2
2312
2313
2314 Default: on.
2315
2316 Package documentation: [SA6005](https://staticcheck.dev/docs/checks/#SA6005)
2317
2318 <a id='SA6006'></a>
2319 ## `SA6006`: Using io.WriteString to write []byte
2320
2321 Using io.WriteString to write a slice of bytes, as in
2322
2323 io.WriteString(w, string(b))
2324
2325 is both unnecessary and inefficient. Converting from \[]byte to string has to allocate and copy the data, and we could simply use w.Write(b) instead.
2326
2327 Available since
2328
2329 2024.1
2330
2331
2332 Default: on.
2333
2334 Package documentation: [SA6006](https://staticcheck.dev/docs/checks/#SA6006)
2335
2336 <a id='SA9001'></a>
2337 ## `SA9001`: Defers in range loops may not run when you expect them to
2338
2339 Available since
2340
2341 2017.1
2342
2343
2344 Default: off. Enable by setting `"analyses": {"SA9001": true}`.
2345
2346 Package documentation: [SA9001](https://staticcheck.dev/docs/checks/#SA9001)
2347
2348 <a id='SA9002'></a>
2349 ## `SA9002`: Using a non-octal os.FileMode that looks like it was meant to be in octal.
2350
2351 Available since
2352
2353 2017.1
2354
2355
2356 Default: on.
2357
2358 Package documentation: [SA9002](https://staticcheck.dev/docs/checks/#SA9002)
2359
2360 <a id='SA9003'></a>
2361 ## `SA9003`: Empty body in an if or else branch
2362
2363 Available since
2364
2365 2017.1, non-default
2366
2367
2368 Default: off. Enable by setting `"analyses": {"SA9003": true}`.
2369
2370 Package documentation: [SA9003](https://staticcheck.dev/docs/checks/#SA9003)
2371
2372 <a id='SA9004'></a>
2373 ## `SA9004`: Only the first constant has an explicit type
2374
2375 In a constant declaration such as the following:
2376
2377 const (
2378 First byte = 1
2379 Second = 2
2380 )
2381
2382 the constant Second does not have the same type as the constant First. This construct shouldn't be confused with
2383
2384 const (
2385 First byte = iota
2386 Second
2387 )
2388
2389 where First and Second do indeed have the same type. The type is only passed on when no explicit value is assigned to the constant.
2390
2391 When declaring enumerations with explicit values it is therefore important not to write
2392
2393 const (
2394 EnumFirst EnumType = 1
2395 EnumSecond = 2
2396 EnumThird = 3
2397 )
2398
2399 This discrepancy in types can cause various confusing behaviors and bugs.
2400
2401 ### Wrong type in variable declarations {#hdr-Wrong_type_in_variable_declarations}
2402
2403 The most obvious issue with such incorrect enumerations expresses itself as a compile error:
2404
2405 package pkg
2406
2407 const (
2408 EnumFirst uint8 = 1
2409 EnumSecond = 2
2410 )
2411
2412 func fn(useFirst bool) {
2413 x := EnumSecond
2414 if useFirst {
2415 x = EnumFirst
2416 }
2417 }
2418
2419 fails to compile with
2420
2421 ./const.go:11:5: cannot use EnumFirst (type uint8) as type int in assignment
2422
2423 ### Losing method sets {#hdr-Losing_method_sets}
2424
2425 A more subtle issue occurs with types that have methods and optional interfaces. Consider the following:
2426
2427 package main
2428
2429 import "fmt"
2430
2431 type Enum int
2432
2433 func (e Enum) String() string {
2434 return "an enum"
2435 }
2436
2437 const (
2438 EnumFirst Enum = 1
2439 EnumSecond = 2
2440 )
2441
2442 func main() {
2443 fmt.Println(EnumFirst)
2444 fmt.Println(EnumSecond)
2445 }
2446
2447 This code will output
2448
2449 an enum
2450 2
2451
2452 as EnumSecond has no explicit type, and thus defaults to int.
2453
2454 Available since
2455
2456 2019.1
2457
2458
2459 Default: on.
2460
2461 Package documentation: [SA9004](https://staticcheck.dev/docs/checks/#SA9004)
2462
2463 <a id='SA9005'></a>
2464 ## `SA9005`: Trying to marshal a struct with no public fields nor custom marshaling
2465
2466 The encoding/json and encoding/xml packages only operate on exported fields in structs, not unexported ones. It is usually an error to try to (un)marshal structs that only consist of unexported fields.
2467
2468 This check will not flag calls involving types that define custom marshaling behavior, e.g. via MarshalJSON methods. It will also not flag empty structs.
2469
2470 Available since
2471
2472 2019.2
2473
2474
2475 Default: off. Enable by setting `"analyses": {"SA9005": true}`.
2476
2477 Package documentation: [SA9005](https://staticcheck.dev/docs/checks/#SA9005)
2478
2479 <a id='SA9006'></a>
2480 ## `SA9006`: Dubious bit shifting of a fixed size integer value
2481
2482 Bit shifting a value past its size will always clear the value.
2483
2484 For instance:
2485
2486 v := int8(42)
2487 v >>= 8
2488
2489 will always result in 0.
2490
2491 This check flags bit shifting operations on fixed size integer values only. That is, int, uint and uintptr are never flagged to avoid potential false positives in somewhat exotic but valid bit twiddling tricks:
2492
2493 // Clear any value above 32 bits if integers are more than 32 bits.
2494 func f(i int) int {
2495 v := i >> 32
2496 v = v << 32
2497 return i-v
2498 }
2499
2500 Available since
2501
2502 2020.2
2503
2504
2505 Default: on.
2506
2507 Package documentation: [SA9006](https://staticcheck.dev/docs/checks/#SA9006)
2508
2509 <a id='SA9007'></a>
2510 ## `SA9007`: Deleting a directory that shouldn't be deleted
2511
2512 It is virtually never correct to delete system directories such as /tmp or the user's home directory. However, it can be fairly easy to do by mistake, for example by mistakenly using os.TempDir instead of ioutil.TempDir, or by forgetting to add a suffix to the result of os.UserHomeDir.
2513
2514 Writing
2515
2516 d := os.TempDir()
2517 defer os.RemoveAll(d)
2518
2519 in your unit tests will have a devastating effect on the stability of your system.
2520
2521 This check flags attempts at deleting the following directories:
2522
2523 \- os.TempDir - os.UserCacheDir - os.UserConfigDir - os.UserHomeDir
2524
2525 Available since
2526
2527 2022.1
2528
2529
2530 Default: off. Enable by setting `"analyses": {"SA9007": true}`.
2531
2532 Package documentation: [SA9007](https://staticcheck.dev/docs/checks/#SA9007)
2533
2534 <a id='SA9008'></a>
2535 ## `SA9008`: else branch of a type assertion is probably not reading the right value
2536
2537 When declaring variables as part of an if statement (like in 'if foo := ...; foo {'), the same variables will also be in the scope of the else branch. This means that in the following example
2538
2539 if x, ok := x.(int); ok {
2540 // ...
2541 } else {
2542 fmt.Printf("unexpected type %T", x)
2543 }
2544
2545 x in the else branch will refer to the x from x, ok :=; it will not refer to the x that is being type-asserted. The result of a failed type assertion is the zero value of the type that is being asserted to, so x in the else branch will always have the value 0 and the type int.
2546
2547 Available since
2548
2549 2022.1
2550
2551
2552 Default: off. Enable by setting `"analyses": {"SA9008": true}`.
2553
2554 Package documentation: [SA9008](https://staticcheck.dev/docs/checks/#SA9008)
2555
2556 <a id='SA9009'></a>
2557 ## `SA9009`: Ineffectual Go compiler directive
2558
2559 A potential Go compiler directive was found, but is ineffectual as it begins with whitespace.
2560
2561 Available since
2562
2563 2024.1
2564
2565
2566 Default: on.
2567
2568 Package documentation: [SA9009](https://staticcheck.dev/docs/checks/#SA9009)
2569
2570 <a id='ST1000'></a>
2571 ## `ST1000`: Incorrect or missing package comment
2572
2573 Packages must have a package comment that is formatted according to the guidelines laid out in [https://go.dev/wiki/CodeReviewComments#package-comments](https://go.dev/wiki/CodeReviewComments#package-comments).
2574
2575 Available since
2576
2577 2019.1, non-default
2578
2579
2580 Default: off. Enable by setting `"analyses": {"ST1000": true}`.
2581
2582 Package documentation: [ST1000](https://staticcheck.dev/docs/checks/#ST1000)
2583
2584 <a id='ST1001'></a>
2585 ## `ST1001`: Dot imports are discouraged
2586
2587 Dot imports that aren't in external test packages are discouraged.
2588
2589 The dot\_import\_whitelist option can be used to whitelist certain imports.
2590
2591 Quoting Go Code Review Comments:
2592
2593 > The import . form can be useful in tests that, due to circular > dependencies, cannot be made part of the package being tested: > > package foo\_test > > import ( > "bar/testutil" // also imports "foo" > . "foo" > ) > > 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.
2594
2595 Available since
2596
2597 2019.1
2598
2599 Options
2600
2601 dot_import_whitelist
2602
2603
2604 Default: off. Enable by setting `"analyses": {"ST1001": true}`.
2605
2606 Package documentation: [ST1001](https://staticcheck.dev/docs/checks/#ST1001)
2607
2608 <a id='ST1003'></a>
2609 ## `ST1003`: Poorly chosen identifier
2610
2611 Identifiers, such as variable and package names, follow certain rules.
2612
2613 See the following links for details:
2614
2615 \- [https://go.dev/doc/effective\_go#package-names](https://go.dev/doc/effective_go#package-names) - [https://go.dev/doc/effective\_go#mixed-caps](https://go.dev/doc/effective_go#mixed-caps) - [https://go.dev/wiki/CodeReviewComments#initialisms](https://go.dev/wiki/CodeReviewComments#initialisms) - [https://go.dev/wiki/CodeReviewComments#variable-names](https://go.dev/wiki/CodeReviewComments#variable-names)
2616
2617 Available since
2618
2619 2019.1, non-default
2620
2621 Options
2622
2623 initialisms
2624
2625
2626 Default: off. Enable by setting `"analyses": {"ST1003": true}`.
2627
2628 Package documentation: [ST1003](https://staticcheck.dev/docs/checks/#ST1003)
2629
2630 <a id='ST1005'></a>
2631 ## `ST1005`: Incorrectly formatted error string
2632
2633 Error strings follow a set of guidelines to ensure uniformity and good composability.
2634
2635 Quoting Go Code Review Comments:
2636
2637 > 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.
2638
2639 Available since
2640
2641 2019.1
2642
2643
2644 Default: off. Enable by setting `"analyses": {"ST1005": true}`.
2645
2646 Package documentation: [ST1005](https://staticcheck.dev/docs/checks/#ST1005)
2647
2648 <a id='ST1006'></a>
2649 ## `ST1006`: Poorly chosen receiver name
2650
2651 Quoting Go Code Review Comments:
2652
2653 > 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.
2654
2655 Available since
2656
2657 2019.1
2658
2659
2660 Default: off. Enable by setting `"analyses": {"ST1006": true}`.
2661
2662 Package documentation: [ST1006](https://staticcheck.dev/docs/checks/#ST1006)
2663
2664 <a id='ST1008'></a>
2665 ## `ST1008`: A function's error value should be its last return value
2666
2667 A function's error value should be its last return value.
2668
2669 Available since
2670
2671 2019.1
2672
2673
2674 Default: off. Enable by setting `"analyses": {"ST1008": true}`.
2675
2676 Package documentation: [ST1008](https://staticcheck.dev/docs/checks/#ST1008)
2677
2678 <a id='ST1011'></a>
2679 ## `ST1011`: Poorly chosen name for variable of type time.Duration
2680
2681 time.Duration values represent an amount of time, which is represented as a count of nanoseconds. An expression like 5 \* time.Microsecond yields the value 5000. It is therefore not appropriate to suffix a variable of type time.Duration with any time unit, such as Msec or Milli.
2682
2683 Available since
2684
2685 2019.1
2686
2687
2688 Default: off. Enable by setting `"analyses": {"ST1011": true}`.
2689
2690 Package documentation: [ST1011](https://staticcheck.dev/docs/checks/#ST1011)
2691
2692 <a id='ST1012'></a>
2693 ## `ST1012`: Poorly chosen name for error variable
2694
2695 Error variables that are part of an API should be called errFoo or ErrFoo.
2696
2697 Available since
2698
2699 2019.1
2700
2701
2702 Default: off. Enable by setting `"analyses": {"ST1012": true}`.
2703
2704 Package documentation: [ST1012](https://staticcheck.dev/docs/checks/#ST1012)
2705
2706 <a id='ST1013'></a>
2707 ## `ST1013`: Should use constants for HTTP error codes, not magic numbers
2708
2709 HTTP has a tremendous number of status codes. While some of those are well known (200, 400, 404, 500), most of them are not. The net/http package provides constants for all status codes that are part of the various specifications. It is recommended to use these constants instead of hard-coding magic numbers, to vastly improve the readability of your code.
2710
2711 Available since
2712
2713 2019.1
2714
2715 Options
2716
2717 http_status_code_whitelist
2718
2719
2720 Default: off. Enable by setting `"analyses": {"ST1013": true}`.
2721
2722 Package documentation: [ST1013](https://staticcheck.dev/docs/checks/#ST1013)
2723
2724 <a id='ST1015'></a>
2725 ## `ST1015`: A switch's default case should be the first or last case
2726
2727 Available since
2728
2729 2019.1
2730
2731
2732 Default: off. Enable by setting `"analyses": {"ST1015": true}`.
2733
2734 Package documentation: [ST1015](https://staticcheck.dev/docs/checks/#ST1015)
2735
2736 <a id='ST1016'></a>
2737 ## `ST1016`: Use consistent method receiver names
2738
2739 Available since
2740
2741 2019.1, non-default
2742
2743
2744 Default: off. Enable by setting `"analyses": {"ST1016": true}`.
2745
2746 Package documentation: [ST1016](https://staticcheck.dev/docs/checks/#ST1016)
2747
2748 <a id='ST1017'></a>
2749 ## `ST1017`: Don't use Yoda conditions
2750
2751 Yoda conditions are conditions of the kind 'if 42 == x', where the literal is on the left side of the comparison. These are a common idiom in languages in which assignment is an expression, to avoid bugs of the kind 'if (x = 42)'. In Go, which doesn't allow for this kind of bug, we prefer the more idiomatic 'if x == 42'.
2752
2753 Available since
2754
2755 2019.2
2756
2757
2758 Default: off. Enable by setting `"analyses": {"ST1017": true}`.
2759
2760 Package documentation: [ST1017](https://staticcheck.dev/docs/checks/#ST1017)
2761
2762 <a id='ST1018'></a>
2763 ## `ST1018`: Avoid zero-width and control characters in string literals
2764
2765 Available since
2766
2767 2019.2
2768
2769
2770 Default: off. Enable by setting `"analyses": {"ST1018": true}`.
2771
2772 Package documentation: [ST1018](https://staticcheck.dev/docs/checks/#ST1018)
2773
2774 <a id='ST1019'></a>
2775 ## `ST1019`: Importing the same package multiple times
2776
2777 Go allows importing the same package multiple times, as long as different import aliases are being used. That is, the following bit of code is valid:
2778
2779 import (
2780 "fmt"
2781 fumpt "fmt"
2782 format "fmt"
2783 )
2784
2785 However, this is very rarely done on purpose. Usually, it is a sign of code that got refactored, accidentally adding duplicate import statements. It is also a rarely known feature, which may contribute to confusion.
2786
2787 Do note that sometimes, this feature may be used intentionally (see for example [https://github.com/golang/go/commit/3409ce39bfd7584523b7a8c150a310cea92d879d](https://github.com/golang/go/commit/3409ce39bfd7584523b7a8c150a310cea92d879d)) – if you want to allow this pattern in your code base, you're advised to disable this check.
2788
2789 It is acceptable to import the same package twice if one of the imports uses the blank identifier. This is allowed in order to increase resilience against erroneous changes when using the same package for its side effects as well as its exported API.
2790
2791 Available since
2792
2793 2020.1
2794
2795
2796 Default: off. Enable by setting `"analyses": {"ST1019": true}`.
2797
2798 Package documentation: [ST1019](https://staticcheck.dev/docs/checks/#ST1019)
2799
2800 <a id='ST1020'></a>
2801 ## `ST1020`: The documentation of an exported function should start with the function's name
2802
2803 Doc comments work best as complete sentences, which allow a wide variety of automated presentations. The first sentence should be a one-sentence summary that starts with the name being declared.
2804
2805 If every doc comment begins with the name of the item it describes, you can use the doc subcommand of the go tool and run the output through grep.
2806
2807 See [https://go.dev/doc/effective\_go#commentary](https://go.dev/doc/effective_go#commentary) for more information on how to write good documentation.
2808
2809 Available since
2810
2811 2020.1, non-default
2812
2813
2814 Default: off. Enable by setting `"analyses": {"ST1020": true}`.
2815
2816 Package documentation: [ST1020](https://staticcheck.dev/docs/checks/#ST1020)
2817
2818 <a id='ST1021'></a>
2819 ## `ST1021`: The documentation of an exported type should start with type's name
2820
2821 Doc comments work best as complete sentences, which allow a wide variety of automated presentations. The first sentence should be a one-sentence summary that starts with the name being declared.
2822
2823 If every doc comment begins with the name of the item it describes, you can use the doc subcommand of the go tool and run the output through grep.
2824
2825 See [https://go.dev/doc/effective\_go#commentary](https://go.dev/doc/effective_go#commentary) for more information on how to write good documentation.
2826
2827 Available since
2828
2829 2020.1, non-default
2830
2831
2832 Default: off. Enable by setting `"analyses": {"ST1021": true}`.
2833
2834 Package documentation: [ST1021](https://staticcheck.dev/docs/checks/#ST1021)
2835
2836 <a id='ST1022'></a>
2837 ## `ST1022`: The documentation of an exported variable or constant should start with variable's name
2838
2839 Doc comments work best as complete sentences, which allow a wide variety of automated presentations. The first sentence should be a one-sentence summary that starts with the name being declared.
2840
2841 If every doc comment begins with the name of the item it describes, you can use the doc subcommand of the go tool and run the output through grep.
2842
2843 See [https://go.dev/doc/effective\_go#commentary](https://go.dev/doc/effective_go#commentary) for more information on how to write good documentation.
2844
2845 Available since
2846
2847 2020.1, non-default
2848
2849
2850 Default: off. Enable by setting `"analyses": {"ST1022": true}`.
2851
2852 Package documentation: [ST1022](https://staticcheck.dev/docs/checks/#ST1022)
2853
2854 <a id='ST1023'></a>
2855 ## `ST1023`: Redundant type in variable declaration
2856
2857 Available since
2858
2859 2021.1, non-default
2860
2861
2862 Default: off. Enable by setting `"analyses": {"ST1023": true}`.
2863
2864 Package documentation: [ST1023](https://staticcheck.dev/docs/checks/#)
2865
2866 <a id='any'></a>
2867 ## `any`: replace interface{} with any
2868
2869 The any analyzer suggests replacing uses of the empty interface type, \`interface{}\`, with the \`any\` alias, which was introduced in Go 1.18. This is a purely stylistic change that makes code more readable.
2870
2871
2872 Default: on.
2873
2874 Package documentation: [any](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#any)
2875
2876 <a id='appendclipped'></a>
2877 ## `appendclipped`: simplify append chains using slices.Concat
2878
2879 The appendclipped analyzer suggests replacing chains of append calls with a single call to slices.Concat, which was added in Go 1.21. For example, append(append(s, s1...), s2...) would be simplified to slices.Concat(s, s1, s2).
2880
2881 In the simple case of appending to a newly allocated slice, such as append(\[]T(nil), s...), the analyzer suggests the more concise slices.Clone(s). For byte slices, it will prefer bytes.Clone if the "bytes" package is already imported.
2882
2883 This fix is only applied when the base of the append tower is a "clipped" slice, meaning its length and capacity are equal (e.g. x\[:0:0] or \[]T{}). This is to avoid changing program behavior by eliminating intended side effects on the base slice's underlying array.
2884
2885 This analyzer is currently disabled by default as the transformation does not preserve the nilness of the base slice in all cases; see [https://go.dev/issue/73557](https://go.dev/issue/73557).
2886
2887
2888 Default: off. Enable by setting `"analyses": {"appendclipped": true}`.
2889
2890 Package documentation: [appendclipped](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#appendclipped)
2891
2892 <a id='appends'></a>
2893 ## `appends`: check for missing values after append
2894
2895 This checker reports calls to append that pass no values to be appended to the slice.
2896
2897 s := []string{"a", "b", "c"}
2898 _ = append(s)
2899
2900 Such calls are always no-ops and often indicate an underlying mistake.
2901
2902
2903 Default: on.
2904
2905 Package documentation: [appends](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/appends)
2906
2907 <a id='asmdecl'></a>
2908 ## `asmdecl`: report mismatches between assembly files and Go declarations
2909
2910
2911
2912 Default: on.
2913
2914 Package documentation: [asmdecl](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/asmdecl)
2915
2916 <a id='assign'></a>
2917 ## `assign`: check for useless assignments
2918
2919 This checker reports assignments of the form x = x or a\[i] = a\[i]. These are almost always useless, and even when they aren't they are usually a mistake.
2920
2921
2922 Default: on.
2923
2924 Package documentation: [assign](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/assign)
2925
2926 <a id='atomic'></a>
2927 ## `atomic`: check for common mistakes using the sync/atomic package
2928
2929 The atomic checker looks for assignment statements of the form:
2930
2931 x = atomic.AddUint64(&x, 1)
2932
2933 which are not atomic.
2934
2935
2936 Default: on.
2937
2938 Package documentation: [atomic](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/atomic)
2939
2940 <a id='atomicalign'></a>
2941 ## `atomicalign`: check for non-64-bits-aligned arguments to sync/atomic functions
2942
2943
2944
2945 Default: on.
2946
2947 Package documentation: [atomicalign](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/atomicalign)
2948
2949 <a id='atomictypes'></a>
2950 ## `atomictypes`: replace basic types in sync/atomic calls with atomic types
2951
2952 The atomictypes analyzer suggests replacing the primitive sync/atomic functions with the strongly typed atomic wrapper types introduced in Go1.19 (e.g. atomic.Int32). For example,
2953
2954 var x int32
2955 atomic.AddInt32(&x, 1)
2956
2957 would become
2958
2959 var x atomic.Int32
2960 x.Add(1)
2961
2962 The atomic types are safer because they don't allow non-atomic access, which is a common source of bugs. These types also resolve memory alignment issues that plagued the old atomic functions on 32-bit architectures.
2963
2964
2965 Default: on.
2966
2967 Package documentation: [atomictypes](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#atomictypes)
2968
2969 <a id='bloop'></a>
2970 ## `bloop`: replace for-range over b.N with b.Loop
2971
2972 The bloop analyzer suggests replacing benchmark loops of the form \`for i := 0; i \< b.N; i++\` or \`for range b.N\` with the more modern \`for b.Loop()\`, which was added in Go 1.24.
2973
2974 This change makes benchmark code more readable and also removes the need for manual timer control, so any preceding calls to b.StartTimer, b.StopTimer, or b.ResetTimer within the same function will also be removed.
2975
2976 Caveats: The b.Loop() method is designed to prevent the compiler from optimizing away the benchmark loop, which can occasionally result in slower execution due to increased allocations in some specific cases. Since its fix may change the performance of nanosecond-scale benchmarks, bloop is disabled by default in the \`go fix\` analyzer suite; see golang/go#74967.
2977
2978
2979 Default: on.
2980
2981 Package documentation: [bloop](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#bloop)
2982
2983 <a id='bools'></a>
2984 ## `bools`: check for common mistakes involving boolean operators
2985
2986
2987
2988 Default: on.
2989
2990 Package documentation: [bools](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/bools)
2991
2992 <a id='buildtag'></a>
2993 ## `buildtag`: check //go:build and // +build directives
2994
2995
2996
2997 Default: on.
2998
2999 Package documentation: [buildtag](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/buildtag)
3000
3001 <a id='cgocall'></a>
3002 ## `cgocall`: detect some violations of the cgo pointer passing rules
3003
3004 Check for invalid cgo pointer passing. This looks for code that uses cgo to call C code passing values whose types are almost always invalid according to the cgo pointer sharing rules. Specifically, it warns about attempts to pass a Go chan, map, func, or slice to C, either directly, or via a pointer, array, or struct.
3005
3006
3007 Default: on.
3008
3009 Package documentation: [cgocall](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/cgocall)
3010
3011 <a id='composites'></a>
3012 ## `composites`: check for unkeyed composite literals
3013
3014 This analyzer reports a diagnostic for composite literals of struct types imported from another package that do not use the field-keyed syntax. Such literals are fragile because the addition of a new field (even if unexported) to the struct will cause compilation to fail.
3015
3016 As an example,
3017
3018 err = &net.DNSConfigError{err}
3019
3020 should be replaced by:
3021
3022 err = &net.DNSConfigError{Err: err}
3023
3024
3025 Default: on.
3026
3027 Package documentation: [composites](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/composite)
3028
3029 <a id='copylocks'></a>
3030 ## `copylocks`: check for locks erroneously passed by value
3031
3032 Inadvertently copying a value containing a lock, such as sync.Mutex or sync.WaitGroup, may cause both copies to malfunction. Generally such values should be referred to through a pointer.
3033
3034
3035 Default: on.
3036
3037 Package documentation: [copylocks](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/copylock)
3038
3039 <a id='deepequalerrors'></a>
3040 ## `deepequalerrors`: check for calls of reflect.DeepEqual on error values
3041
3042 The deepequalerrors checker looks for calls of the form:
3043
3044 reflect.DeepEqual(err1, err2)
3045
3046 where err1 and err2 are errors. Using reflect.DeepEqual to compare errors is discouraged.
3047
3048
3049 Default: on.
3050
3051 Package documentation: [deepequalerrors](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/deepequalerrors)
3052
3053 <a id='defers'></a>
3054 ## `defers`: report common mistakes in defer statements
3055
3056 The defers analyzer reports a diagnostic when a defer statement would result in a non-deferred call to time.Since, as experience has shown that this is nearly always a mistake.
3057
3058 For example:
3059
3060 start := time.Now()
3061 ...
3062 defer recordLatency(time.Since(start)) // error: call to time.Since is not deferred
3063
3064 The correct code is:
3065
3066 defer func() { recordLatency(time.Since(start)) }()
3067
3068
3069 Default: on.
3070
3071 Package documentation: [defers](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/defers)
3072
3073 <a id='deprecated'></a>
3074 ## `deprecated`: check for use of deprecated identifiers
3075
3076 The deprecated analyzer looks for deprecated symbols and package imports.
3077
3078 See [https://go.dev/wiki/Deprecated](https://go.dev/wiki/Deprecated) to learn about Go's convention for documenting and signaling deprecated identifiers.
3079
3080
3081 Default: on.
3082
3083 Package documentation: [deprecated](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/deprecated)
3084
3085 <a id='directive'></a>
3086 ## `directive`: check Go toolchain directives such as //go:debug
3087
3088 This analyzer checks for problems with known Go toolchain directives in all Go source files in a package directory, even those excluded by //go:build constraints, and all non-Go source files too.
3089
3090 For //go:debug (see [https://go.dev/doc/godebug](https://go.dev/doc/godebug)), the analyzer checks that the directives are placed only in Go source files, only above the package comment, and only in package main or \*\_test.go files.
3091
3092 Support for other known directives may be added in the future.
3093
3094 This analyzer does not check //go:build, which is handled by the buildtag analyzer.
3095
3096
3097 Default: on.
3098
3099 Package documentation: [directive](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/directive)
3100
3101 <a id='embed'></a>
3102 ## `embed`: check //go:embed directive usage
3103
3104 This analyzer checks that the embed package is imported if //go:embed directives are present, providing a suggested fix to add the import if it is missing.
3105
3106 This analyzer also checks that //go:embed directives precede the declaration of a single variable.
3107
3108
3109 Default: on.
3110
3111 Package documentation: [embed](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/embeddirective)
3112
3113 <a id='embedlit'></a>
3114 ## `embedlit`: simplify references to embedded fields in composite literals
3115
3116 The embedlit analyzer suggests removing redundant embedded field type specifiers from composite literals. Go1.27 introduced the ability to directly initialize fields promoted from embedded struct types without a nested literal. For example, given the following structs:
3117
3118 type T struct {
3119 U
3120 }
3121
3122 type U struct {
3123 x int
3124 }
3125
3126 A composite literal such as
3127
3128 t := T{U: U{x: 1}}
3129
3130 would become
3131
3132 t := T{x: 1}
3133
3134
3135 Default: on.
3136
3137 Package documentation: [embedlit](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#embedlit)
3138
3139 <a id='errorsas'></a>
3140 ## `errorsas`: report passing non-pointer or non-error values to errors.As
3141
3142 The errorsas analyzer reports calls to errors.As where the type of the second argument is not a pointer to a type implementing error. For example:
3143
3144 var unwrappedErr net.DNSError
3145 errors.As(err, unwrappedErr) // should use &unwrappedErr, DNSError.Error has a pointer receiver
3146
3147
3148 Default: on.
3149
3150 Package documentation: [errorsas](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/errorsas)
3151
3152 <a id='errorsastype'></a>
3153 ## `errorsastype`: replace errors.As with errors.AsType[T]
3154
3155 This analyzer suggests fixes to simplify uses of [errors.As](/errors#As) of this form:
3156
3157 var myerr *MyErr
3158 if errors.As(err, &myerr) {
3159 handle(myerr)
3160 }
3161
3162 by using the less error-prone generic [errors.AsType](/errors#AsType) function, introduced in Go 1.26:
3163
3164 if myerr, ok := errors.AsType[*MyErr](err); ok {
3165 handle(myerr)
3166 }
3167
3168 The fix is only offered if the var declaration has the form shown and there are no uses of myerr outside the if statement.
3169
3170
3171 Default: on.
3172
3173 Package documentation: [errorsastype](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#errorsastype)
3174
3175 <a id='errorsastypeshadow'></a>
3176 ## `errorsastypeshadow`: report shadowing of errors.AsType[T] in if/else chains
3177
3178 For example:
3179
3180 err := f()
3181 if err, ok := errors.AsType[*FooErr](err); ok {
3182 useFoo(err)
3183 } else if err, ok := errors.AsType[*BarErr](err); ok {
3184 useBar(err)
3185 }
3186
3187 In this case, the second call to errors.AsType does not operate on the original error. Instead, its operand is the zero value of type \*FooErr produced by the first if statement; this is invariably a mistake.
3188
3189
3190 Default: on.
3191
3192 Package documentation: [errorsastypeshadow](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/errorsastypeshadow)
3193
3194 <a id='fieldalignment'></a>
3195 ## `fieldalignment`: find structs that would use less memory if their fields were sorted
3196
3197 This analyzer finds structs that can be rearranged to use less memory, and provides a suggested edit with the most compact order.
3198
3199 Note that there are two different diagnostics reported. One checks struct size, and the other reports "pointer bytes" used. Pointer bytes is how many bytes of the object that the garbage collector has to potentially scan for pointers, for example:
3200
3201 struct { uint32; string }
3202
3203 have 16 pointer bytes because the garbage collector has to scan up through the string's inner pointer.
3204
3205 struct { string; *uint32 }
3206
3207 has 24 pointer bytes because it has to scan further through the \*uint32.
3208
3209 struct { string; uint32 }
3210
3211 has 8 because it can stop immediately after the string pointer.
3212
3213 Be aware that the most compact order is not always the most efficient. In rare cases it may cause two variables each updated by its own goroutine to occupy the same CPU cache line, inducing a form of memory contention known as "false sharing" that slows down both goroutines.
3214
3215 Unlike most analyzers, which report likely mistakes, the diagnostics produced by fieldanalyzer very rarely indicate a significant problem, so the analyzer is not included in typical suites such as vet or gopls. Use this standalone command to run it on your code:
3216
3217 $ go install golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment@latest
3218 $ fieldalignment [packages]
3219
3220
3221 Default: off. Enable by setting `"analyses": {"fieldalignment": true}`.
3222
3223 Package documentation: [fieldalignment](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/fieldalignment)
3224
3225 <a id='fillreturns'></a>
3226 ## `fillreturns`: suggest fixes for errors due to an incorrect number of return values
3227
3228 This checker provides suggested fixes for type errors of the type "wrong number of return values (want %d, got %d)". For example:
3229
3230 func m() (int, string, *bool, error) {
3231 return
3232 }
3233
3234 will turn into
3235
3236 func m() (int, string, *bool, error) {
3237 return 0, "", nil, nil
3238 }
3239
3240 This functionality is similar to [https://github.com/sqs/goreturns](https://github.com/sqs/goreturns).
3241
3242
3243 Default: on.
3244
3245 Package documentation: [fillreturns](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/fillreturns)
3246
3247 <a id='fmtappendf'></a>
3248 ## `fmtappendf`: replace []byte(fmt.Sprintf) with fmt.Appendf
3249
3250 The fmtappendf analyzer suggests replacing \`\[]byte(fmt.Sprintf(...))\` with \`fmt.Appendf(nil, ...)\`. This avoids the intermediate allocation of a string by Sprintf, making the code more efficient. The suggestion also applies to fmt.Sprint and fmt.Sprintln.
3251
3252 Since its fix is not a Pareto improvement, fmtappendf is disabled by default in the \`go fix\` analyzer suite; see golang/go#77581.
3253
3254
3255 Default: on.
3256
3257 Package documentation: [fmtappendf](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#fmtappendf)
3258
3259 <a id='forvar'></a>
3260 ## `forvar`: remove redundant re-declaration of loop variables
3261
3262 The forvar analyzer removes unnecessary shadowing of loop variables. Before Go 1.22, it was common to write \`for \_, x := range s { x := x ... }\` to create a fresh variable for each iteration. Go 1.22 changed the semantics of \`for\` loops, making this pattern redundant. This analyzer removes the unnecessary \`x := x\` statement.
3263
3264 This fix only applies to \`range\` loops.
3265
3266
3267 Default: on.
3268
3269 Package documentation: [forvar](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#forvar)
3270
3271 <a id='framepointer'></a>
3272 ## `framepointer`: report assembly that clobbers the frame pointer before saving it
3273
3274
3275
3276 Default: on.
3277
3278 Package documentation: [framepointer](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/framepointer)
3279
3280 <a id='hostport'></a>
3281 ## `hostport`: check format of addresses passed to net.Dial
3282
3283 This analyzer flags code that produce network address strings using fmt.Sprintf, as in this example:
3284
3285 addr := fmt.Sprintf("%s:%d", host, 12345) // "will not work with IPv6"
3286 ...
3287 conn, err := net.Dial("tcp", addr) // "when passed to dial here"
3288
3289 The analyzer suggests a fix to use the correct approach, a call to net.JoinHostPort:
3290
3291 addr := net.JoinHostPort(host, "12345")
3292 ...
3293 conn, err := net.Dial("tcp", addr)
3294
3295 A similar diagnostic and fix are produced for a format string of "%s:%s".
3296
3297
3298 Default: on.
3299
3300 Package documentation: [hostport](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/hostport)
3301
3302 <a id='httpresponse'></a>
3303 ## `httpresponse`: check for mistakes using HTTP responses
3304
3305 A common mistake when using the net/http package is to defer a function call to close the http.Response Body before checking the error that determines whether the response is valid:
3306
3307 resp, err := http.Head(url)
3308 defer resp.Body.Close()
3309 if err != nil {
3310 log.Fatal(err)
3311 }
3312 // (defer statement belongs here)
3313
3314 This checker helps uncover latent nil dereference bugs by reporting a diagnostic for such mistakes.
3315
3316
3317 Default: on.
3318
3319 Package documentation: [httpresponse](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/httpresponse)
3320
3321 <a id='ifaceassert'></a>
3322 ## `ifaceassert`: detect impossible interface-to-interface type assertions
3323
3324 This checker flags type assertions v.(T) and corresponding type-switch cases in which the static type V of v is an interface that cannot possibly implement the target interface T. This occurs when V and T contain methods with the same name but different signatures. Example:
3325
3326 var v interface {
3327 Read()
3328 }
3329 _ = v.(io.Reader)
3330
3331 The Read method in v has a different signature than the Read method in io.Reader, so this assertion cannot succeed.
3332
3333
3334 Default: on.
3335
3336 Package documentation: [ifaceassert](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/ifaceassert)
3337
3338 <a id='infertypeargs'></a>
3339 ## `infertypeargs`: check for unnecessary type arguments in call expressions
3340
3341 Explicit type arguments may be omitted from call expressions if they can be inferred from function arguments, or from other type arguments:
3342
3343 func f[T any](T) {}
3344
3345 func _() {
3346 f[string]("foo") // string could be inferred
3347 }
3348
3349
3350 Default: on.
3351
3352 Package documentation: [infertypeargs](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/infertypeargs)
3353
3354 <a id='inline'></a>
3355 ## `inline`: apply fixes based on 'go:fix inline' comment directives
3356
3357 The inline analyzer inlines functions, constants, and type aliases that are marked for inlining.
3358
3359 Use this command to apply (just) inline fixes en masse:
3360
3361 $ go fix -inline ./...
3362
3363 \## Functions
3364
3365 Given a function that is marked for inlining, like this one:
3366
3367 //go:fix inline
3368 func Square(x int) int { return Pow(x, 2) }
3369
3370 this analyzer will recommend that calls to the function elsewhere, in the same or other packages, should be inlined.
3371
3372 Inlining can be used to move off of a deprecated function:
3373
3374 // Deprecated: prefer Pow(x, 2).
3375 //go:fix inline
3376 func Square(x int) int { return Pow(x, 2) }
3377
3378 It can also be used to move off of an obsolete package, as when the import path has changed or a higher major version is available:
3379
3380 package pkg
3381
3382 import pkg2 "pkg/v2"
3383
3384 //go:fix inline
3385 func F() { pkg2.F(nil) }
3386
3387 Replacing a call pkg.F() by pkg2.F(nil) can have no effect on the program, so this mechanism provides a low-risk way to update large numbers of calls. We recommend, where possible, expressing the old API in terms of the new one to enable automatic migration.
3388
3389 The inliner takes care to avoid behavior changes, even subtle ones, such as changes to the order in which argument expressions are evaluated. When it cannot safely eliminate all parameter variables, it may introduce a "binding declaration" of the form
3390
3391 var params = args
3392
3393 to evaluate argument expressions in the correct order and bind them to parameter variables. Since the resulting code transformation may be stylistically suboptimal, such inlinings may be disabled by specifying the -inline.allow\_binding\_decl=false flag to the analyzer driver.
3394
3395 (In cases where it is not safe to "reduce" a call—that is, to replace a call f(x) by the body of function f, suitably substituted—the inliner machinery is capable of replacing f by a function literal, func(){...}(). However, the inline analyzer discards all such "literalizations" unconditionally, again on grounds of style.)
3396
3397 \## Constants
3398
3399 Given a constant that is marked for inlining, like this one:
3400
3401 //go:fix inline
3402 const Ptr = Pointer
3403
3404 this analyzer will recommend that uses of Ptr should be replaced with Pointer.
3405
3406 As with functions, inlining can be used to replace deprecated constants and constants in obsolete packages.
3407
3408 A constant definition can be marked for inlining only if it refers to another named constant.
3409
3410 The "//go:fix inline" comment must appear before a single const declaration on its own, as above; before a const declaration that is part of a group, as in this case:
3411
3412 const (
3413 C = 1
3414 //go:fix inline
3415 Ptr = Pointer
3416 )
3417
3418 or before a group, applying to every constant in the group:
3419
3420 //go:fix inline
3421 const (
3422 Ptr = Pointer
3423 Val = Value
3424 )
3425
3426 \## Type aliases
3427
3428 Similar to named constants, a type alias can also be marked for inlining:
3429
3430 //go:fix inline
3431 type A = newpkg.A
3432
3433 The analyzer will replace all references to the annotated type (A) by the type on the right-hand side of the declaration (newpkg.A).
3434
3435 \## Tests
3436
3437 A use of a function, named constant, or type alias X from its dedicated test (TestX), is not inlined, since the purpose of the test is to exercise X itself, even if it is deprecated and other uses of it should be inlined. This applies to benchmarks and examples too, and follows the usual conventions of test function naming.
3438
3439 Similarly, if the symbol X is declared in a file named foo.go, any use of it within a file named foo\_test.go will also not be inlined.
3440
3441
3442 Default: on.
3443
3444 Package documentation: [inline](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/inline)
3445
3446 <a id='loopclosure'></a>
3447 ## `loopclosure`: check references to loop variables from within nested functions
3448
3449 This analyzer reports places where a function literal references the iteration variable of an enclosing loop, and the loop calls the function in such a way (e.g. with go or defer) that it may outlive the loop iteration and possibly observe the wrong value of the variable.
3450
3451 Note: An iteration variable can only outlive a loop iteration in Go versions \<=1.21. In Go 1.22 and later, the loop variable lifetimes changed to create a new iteration variable per loop iteration. (See go.dev/issue/60078.)
3452
3453 In this example, all the deferred functions run after the loop has completed, so all observe the final value of v \[\<go1.22].
3454
3455 for _, v := range list {
3456 defer func() {
3457 use(v) // incorrect
3458 }()
3459 }
3460
3461 One fix is to create a new variable for each iteration of the loop:
3462
3463 for _, v := range list {
3464 v := v // new var per iteration
3465 defer func() {
3466 use(v) // ok
3467 }()
3468 }
3469
3470 After Go version 1.22, the previous two for loops are equivalent and both are correct.
3471
3472 The next example uses a go statement and has a similar problem \[\<go1.22]. In addition, it has a data race because the loop updates v concurrent with the goroutines accessing it.
3473
3474 for _, v := range elem {
3475 go func() {
3476 use(v) // incorrect, and a data race
3477 }()
3478 }
3479
3480 A fix is the same as before. The checker also reports problems in goroutines started by golang.org/x/sync/errgroup.Group. A hard-to-spot variant of this form is common in parallel tests:
3481
3482 func Test(t *testing.T) {
3483 for _, test := range tests {
3484 t.Run(test.name, func(t *testing.T) {
3485 t.Parallel()
3486 use(test) // incorrect, and a data race
3487 })
3488 }
3489 }
3490
3491 The t.Parallel() call causes the rest of the function to execute concurrent with the loop \[\<go1.22].
3492
3493 The analyzer reports references only in the last statement, as it is not deep enough to understand the effects of subsequent statements that might render the reference benign. ("Last statement" is defined recursively in compound statements such as if, switch, and select.)
3494
3495 See: [https://golang.org/doc/go\_faq.html#closures\_and\_goroutines](https://golang.org/doc/go_faq.html#closures_and_goroutines)
3496
3497
3498 Default: on.
3499
3500 Package documentation: [loopclosure](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/loopclosure)
3501
3502 <a id='lostcancel'></a>
3503 ## `lostcancel`: check cancel func returned by context.WithCancel is called
3504
3505 The cancellation function returned by context.WithCancel, WithTimeout, WithDeadline and variants such as WithCancelCause must be called, or the new context will remain live until its parent context is cancelled. (The background context is never cancelled.)
3506
3507
3508 Default: on.
3509
3510 Package documentation: [lostcancel](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/lostcancel)
3511
3512 <a id='maprange'></a>
3513 ## `maprange`: checks for unnecessary calls to maps.Keys and maps.Values in range statements
3514
3515 Consider a loop written like this:
3516
3517 for val := range maps.Values(m) {
3518 fmt.Println(val)
3519 }
3520
3521 This should instead be written without the call to maps.Values:
3522
3523 for _, val := range m {
3524 fmt.Println(val)
3525 }
3526
3527 golang.org/x/exp/maps returns slices for Keys/Values instead of iterators, but unnecessary calls should similarly be removed:
3528
3529 for _, key := range maps.Keys(m) {
3530 fmt.Println(key)
3531 }
3532
3533 should be rewritten as:
3534
3535 for key := range m {
3536 fmt.Println(key)
3537 }
3538
3539
3540 Default: on.
3541
3542 Package documentation: [maprange](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/maprange)
3543
3544 <a id='mapsloop'></a>
3545 ## `mapsloop`: replace explicit loops over maps with calls to maps package
3546
3547 The mapsloop analyzer replaces loops of the form
3548
3549 for k, v := range x { m[k] = v }
3550
3551 with a single call to a function from the \`maps\` package, added in Go 1.23. Depending on the context, this could be \`maps.Copy\`, \`maps.Insert\`, \`maps.Clone\`, or \`maps.Collect\`.
3552
3553 The transformation to \`maps.Clone\` is applied conservatively, as it preserves the nilness of the source map, which may be a subtle change in behavior if the original code did not handle a nil map in the same way.
3554
3555
3556 Default: on.
3557
3558 Package documentation: [mapsloop](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#mapsloop)
3559
3560 <a id='minmax'></a>
3561 ## `minmax`: replace if/else statements with calls to min or max
3562
3563 The minmax analyzer simplifies conditional assignments by suggesting the use of the built-in \`min\` and \`max\` functions, introduced in Go 1.21. For example,
3564
3565 if a < b { x = a } else { x = b }
3566
3567 is replaced by
3568
3569 x = min(a, b).
3570
3571 This analyzer avoids making suggestions for floating-point types, as the behavior of \`min\` and \`max\` with NaN values can differ from the original if/else statement.
3572
3573
3574 Default: on.
3575
3576 Package documentation: [minmax](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#minmax)
3577
3578 <a id='newexpr'></a>
3579 ## `newexpr`: simplify code by using go1.26's new(expr)
3580
3581 This analyzer finds declarations of functions of this form:
3582
3583 func varOf(x int) *int { return &x }
3584
3585 and suggests a fix to turn them into inlinable wrappers around go1.26's built-in new(expr) function:
3586
3587 //go:fix inline
3588 func varOf(x int) *int { return new(x) }
3589
3590 (The directive comment causes the 'inline' analyzer to suggest that calls to such functions are inlined.)
3591
3592 In addition, this analyzer suggests a fix for each call to one of the functions before it is transformed, so that
3593
3594 use(varOf(123))
3595
3596 is replaced by:
3597
3598 use(new(123))
3599
3600 Wrapper functions such as varOf are common when working with Go serialization packages such as for JSON or protobuf, where pointers are often used to express optionality.
3601
3602
3603 Default: on.
3604
3605 Package documentation: [newexpr](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#newexpr)
3606
3607 <a id='nilfunc'></a>
3608 ## `nilfunc`: check for useless comparisons between functions and nil
3609
3610 A useless comparison is one like f == nil as opposed to f() == nil.
3611
3612
3613 Default: on.
3614
3615 Package documentation: [nilfunc](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/nilfunc)
3616
3617 <a id='nilness'></a>
3618 ## `nilness`: check for redundant or impossible nil comparisons
3619
3620 The nilness checker inspects the control-flow graph of each function in a package and reports nil pointer dereferences, degenerate nil pointers, and panics with nil values. A degenerate comparison is of the form x==nil or x!=nil where x is statically known to be nil or non-nil. These are often a mistake, especially in control flow related to errors. Panics with nil values are checked because they are not detectable by
3621
3622 if r := recover(); r != nil {
3623
3624 This check reports conditions such as:
3625
3626 if f == nil { // impossible condition (f is a function)
3627 }
3628
3629 and:
3630
3631 p := &v
3632 ...
3633 if p != nil { // tautological condition
3634 }
3635
3636 and:
3637
3638 if p == nil {
3639 print(*p) // nil dereference
3640 }
3641
3642 and:
3643
3644 if p == nil {
3645 panic(p)
3646 }
3647
3648 Sometimes the control flow may be quite complex, making bugs hard to spot. In the example below, the err.Error expression is guaranteed to panic because, after the first return, err must be nil. The intervening loop is just a distraction.
3649
3650 ...
3651 err := g.Wait()
3652 if err != nil {
3653 return err
3654 }
3655 partialSuccess := false
3656 for _, err := range errs {
3657 if err == nil {
3658 partialSuccess = true
3659 break
3660 }
3661 }
3662 if partialSuccess {
3663 reportStatus(StatusMessage{
3664 Code: code.ERROR,
3665 Detail: err.Error(), // "nil dereference in dynamic method call"
3666 })
3667 return nil
3668 }
3669
3670 ...
3671
3672
3673 Default: on.
3674
3675 Package documentation: [nilness](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/nilness)
3676
3677 <a id='nonewvars'></a>
3678 ## `nonewvars`: suggested fixes for "no new vars on left side of :="
3679
3680 This checker provides suggested fixes for type errors of the type "no new vars on left side of :=". For example:
3681
3682 z := 1
3683 z := 2
3684
3685 will turn into
3686
3687 z := 1
3688 z = 2
3689
3690
3691 Default: on.
3692
3693 Package documentation: [nonewvars](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/nonewvars)
3694
3695 <a id='noresultvalues'></a>
3696 ## `noresultvalues`: suggested fixes for unexpected return values
3697
3698 This checker provides suggested fixes for type errors of the type "no result values expected" or "too many return values". For example:
3699
3700 func z() { return nil }
3701
3702 will turn into
3703
3704 func z() { return }
3705
3706
3707 Default: on.
3708
3709 Package documentation: [noresultvalues](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/noresultvalues)
3710
3711 <a id='omitzero'></a>
3712 ## `omitzero`: suggest replacing omitempty with omitzero for struct fields
3713
3714 The omitzero analyzer identifies uses of the \`omitempty\` JSON struct tag on fields that are themselves structs. For struct-typed fields, the \`omitempty\` tag has no effect on the behavior of json.Marshal and json.Unmarshal. The analyzer offers two suggestions: either remove the tag, or replace it with \`omitzero\` (added in Go 1.24), which correctly omits the field if the struct value is zero.
3715
3716 However, some other serialization packages (notably kubebuilder, see [https://book.kubebuilder.io/reference/markers.html](https://book.kubebuilder.io/reference/markers.html)) may have their own interpretation of the \`json:",omitzero"\` tag, so removing it may affect program behavior. For this reason, the omitzero modernizer will not make changes in any package that contains +kubebuilder annotations.
3717
3718 Replacing \`omitempty\` with \`omitzero\` is a change in behavior. The original code would always encode the struct field, whereas the modified code will omit it if it is a zero-value.
3719
3720
3721 Default: on.
3722
3723 Package documentation: [omitzero](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#omitzero)
3724
3725 <a id='plusbuild'></a>
3726 ## `plusbuild`: remove obsolete //+build comments
3727
3728 The plusbuild analyzer suggests a fix to remove obsolete build tags of the form:
3729
3730 //+build linux,amd64
3731
3732 in files that also contain a Go 1.18-style tag such as:
3733
3734 //go:build linux && amd64
3735
3736 (It does not check that the old and new tags are consistent; that is the job of the 'buildtag' analyzer in the vet suite.)
3737
3738
3739 Default: on.
3740
3741 Package documentation: [plusbuild](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#plusbuild)
3742
3743 <a id='printf'></a>
3744 ## `printf`: check consistency of Printf format strings and arguments
3745
3746 The check applies to calls of the formatting functions such as [fmt.Printf](/fmt#Printf) and [fmt.Sprintf](/fmt#Sprintf), as well as any detected wrappers of those functions such as [log.Printf](/log#Printf). It reports a variety of mistakes such as syntax errors in the format string and mismatches (of number and type) between the verbs and their arguments.
3747
3748 See the documentation of the fmt package for the complete set of format operators and their operand types.
3749
3750
3751 Default: on.
3752
3753 Package documentation: [printf](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/printf)
3754
3755 <a id='rangeint'></a>
3756 ## `rangeint`: replace 3-clause for loops with for-range over integers
3757
3758 The rangeint analyzer suggests replacing traditional for loops such as
3759
3760 for i := 0; i < n; i++ { ... }
3761
3762 with the more idiomatic Go 1.22 style:
3763
3764 for i := range n { ... }
3765
3766 This transformation is applied only if (a) the loop variable is not modified within the loop body and (b) the loop's limit expression is not modified within the loop, as \`for range\` evaluates its operand only once.
3767
3768
3769 Default: on.
3770
3771 Package documentation: [rangeint](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#rangeint)
3772
3773 <a id='recursiveiter'></a>
3774 ## `recursiveiter`: check for inefficient recursive iterators
3775
3776 This analyzer reports when a function that returns an iterator (iter.Seq or iter.Seq2) calls itself as the operand of a range statement, as this is inefficient.
3777
3778 When implementing an iterator (e.g. iter.Seq\[T]) for a recursive data type such as a tree or linked list, it is tempting to recursively range over the iterator for each child element.
3779
3780 Here's an example of a naive iterator over a binary tree:
3781
3782 type tree struct {
3783 value int
3784 left, right *tree
3785 }
3786
3787 func (t *tree) All() iter.Seq[int] {
3788 return func(yield func(int) bool) {
3789 if t != nil {
3790 for elem := range t.left.All() { // "inefficient recursive iterator"
3791 if !yield(elem) {
3792 return
3793 }
3794 }
3795 if !yield(t.value) {
3796 return
3797 }
3798 for elem := range t.right.All() { // "inefficient recursive iterator"
3799 if !yield(elem) {
3800 return
3801 }
3802 }
3803 }
3804 }
3805 }
3806
3807 Though it correctly enumerates the elements of the tree, it hides a significant performance problem--two, in fact. Consider a balanced tree of N nodes. Iterating the root node will cause All to be called once on every node of the tree. This results in a chain of nested active range-over-func statements when yield(t.value) is called on a leaf node.
3808
3809 The first performance problem is that each range-over-func statement must typically heap-allocate a variable, so iteration of the tree allocates as many variables as there are elements in the tree, for a total of O(N) allocations, all unnecessary.
3810
3811 The second problem is that each call to yield for a leaf of the tree causes each of the enclosing range loops to receive a value, which they then immediately pass on to their respective yield function. This results in a chain of log(N) dynamic yield calls per element, a total of O(N\*log N) dynamic calls overall, when only O(N) are necessary.
3812
3813 A better implementation strategy for recursive iterators is to first define the "every" operator for your recursive data type, where every(f) reports whether an arbitrary predicate f(x) is true for every element x in the data type. For our tree, the every function would be:
3814
3815 func (t *tree) every(f func(int) bool) bool {
3816 return t == nil ||
3817 t.left.every(f) && f(t.value) && t.right.every(f)
3818 }
3819
3820 For example, this use of the every operator prints whether every element in the tree is an even number:
3821
3822 even := func(x int) bool { return x&1 == 0 }
3823 println(t.every(even))
3824
3825 Then the iterator can be simply expressed as a trivial wrapper around the every operator:
3826
3827 func (t *tree) All() iter.Seq[int] {
3828 return func(yield func(int) bool) {
3829 _ = t.every(yield)
3830 }
3831 }
3832
3833 In effect, tree.All computes whether yield returns true for each element, short-circuiting if it ever returns false, then discards the final boolean result.
3834
3835 This has much better performance characteristics: it makes one dynamic call per element of the tree, and it doesn't heap-allocate anything. It is also clearer.
3836
3837
3838 Default: on.
3839
3840 Package documentation: [recursiveiter](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/recursiveiter)
3841
3842 <a id='reflecttypefor'></a>
3843 ## `reflecttypefor`: replace reflect.TypeOf(x) with TypeFor[T]()
3844
3845 This analyzer suggests fixes to replace uses of reflect.TypeOf(x) with reflect.TypeFor, introduced in go1.22, when the desired runtime type is known at compile time, for example:
3846
3847 reflect.TypeOf(uint32(0)) -> reflect.TypeFor[uint32]()
3848 reflect.TypeOf((*ast.File)(nil)) -> reflect.TypeFor[*ast.File]()
3849
3850 It also offers a fix to simplify the constructions below, which use reflect.TypeOf to return the runtime type for an interface type,
3851
3852 reflect.TypeOf((*io.Reader)(nil)).Elem()
3853
3854 or:
3855
3856 reflect.TypeOf([]io.Reader(nil)).Elem()
3857
3858 to:
3859
3860 reflect.TypeFor[io.Reader]()
3861
3862 No fix is offered in cases when the runtime type is dynamic, such as:
3863
3864 var r io.Reader = ...
3865 reflect.TypeOf(r)
3866
3867 or when the operand has potential side effects.
3868
3869
3870 Default: on.
3871
3872 Package documentation: [reflecttypefor](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#reflecttypefor)
3873
3874 <a id='scannererr'></a>
3875 ## `scannererr`: report failure to check bufio.Scanner.Err
3876
3877 This analyzer reports uses of bufio.Scanner in which the result of NewScanner is assigned to a local variable that is then used in a loop that calls Scanner.Scan, but lacks a final check of Scanner.Err, which is how I/O errors are reported.
3878
3879 For example:
3880
3881 sc := bufio.NewScanner(os.Stdin) // error: "bufio.Scanner sc is used in Scan loop without final check of sc.Err()"
3882 for sc.Scan() {
3883 line := sc.Text()
3884 use(line)
3885 }
3886 /* ...no use of sc.Err()... */
3887
3888 To avoid false positives, the analyzer is silent if the scanner is passed into or out of the function or assigned somewhere other than a local variable.
3889
3890 It is not this analyzer's goal to ensure proper handling of errors in all cases, but merely the simple mistakes where the user may have been oblivious to the existence of the Scanner.Err method.
3891
3892 The analyzer ignores calls to bufio.NewScanner whose argument is an infallible memory-backed io.Reader such as strings.Reader or bytes.Buffer. (In such cases, Scan may yet fail if a token or line is too long for the scanner's internal buffer, but this is rare.)
3893
3894 If you know that errors are impossible for a given scanner, you can suppress the diagnostic thus:
3895
3896 _ = sc.Err() // ignore error; neither reading nor scanning can fail
3897
3898
3899 Default: on.
3900
3901 Package documentation: [scannererr](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/scannererr)
3902
3903 <a id='shadow'></a>
3904 ## `shadow`: check for possible unintended shadowing of variables
3905
3906 This analyzer check for shadowed variables. A shadowed variable is a variable declared in an inner scope with the same name and type as a variable in an outer scope, and where the outer variable is mentioned after the inner one is declared.
3907
3908 (This definition can be refined; the module generates too many false positives and is not yet enabled by default.)
3909
3910 For example:
3911
3912 func BadRead(f *os.File, buf []byte) error {
3913 var err error
3914 for {
3915 n, err := f.Read(buf) // shadows the function variable 'err'
3916 if err != nil {
3917 break // causes return of wrong value
3918 }
3919 foo(buf)
3920 }
3921 return err
3922 }
3923
3924
3925 Default: off. Enable by setting `"analyses": {"shadow": true}`.
3926
3927 Package documentation: [shadow](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/shadow)
3928
3929 <a id='shift'></a>
3930 ## `shift`: check for shifts that equal or exceed the width of the integer
3931
3932
3933
3934 Default: on.
3935
3936 Package documentation: [shift](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/shift)
3937
3938 <a id='sigchanyzer'></a>
3939 ## `sigchanyzer`: check for unbuffered channel of os.Signal
3940
3941 This checker reports call expression of the form
3942
3943 signal.Notify(c <-chan os.Signal, sig ...os.Signal),
3944
3945 where c is an unbuffered channel, which can be at risk of missing the signal.
3946
3947
3948 Default: on.
3949
3950 Package documentation: [sigchanyzer](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/sigchanyzer)
3951
3952 <a id='simplifycompositelit'></a>
3953 ## `simplifycompositelit`: check for composite literal simplifications
3954
3955 An array, slice, or map composite literal of the form:
3956
3957 []T{T{}, T{}}
3958
3959 will be simplified to:
3960
3961 []T{{}, {}}
3962
3963 This is one of the simplifications that "gofmt -s" applies.
3964
3965 This analyzer ignores generated code.
3966
3967
3968 Default: on.
3969
3970 Package documentation: [simplifycompositelit](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifycompositelit)
3971
3972 <a id='simplifyrange'></a>
3973 ## `simplifyrange`: check for range statement simplifications
3974
3975 A range of the form:
3976
3977 for x, _ = range v {...}
3978
3979 will be simplified to:
3980
3981 for x = range v {...}
3982
3983 A range of the form:
3984
3985 for _ = range v {...}
3986
3987 will be simplified to:
3988
3989 for range v {...}
3990
3991 This is one of the simplifications that "gofmt -s" applies.
3992
3993 This analyzer ignores generated code.
3994
3995
3996 Default: on.
3997
3998 Package documentation: [simplifyrange](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifyrange)
3999
4000 <a id='simplifyslice'></a>
4001 ## `simplifyslice`: check for slice simplifications
4002
4003 A slice expression of the form:
4004
4005 s[a:len(s)]
4006
4007 will be simplified to:
4008
4009 s[a:]
4010
4011 This is one of the simplifications that "gofmt -s" applies.
4012
4013 This analyzer ignores generated code.
4014
4015
4016 Default: on.
4017
4018 Package documentation: [simplifyslice](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifyslice)
4019
4020 <a id='slicesbackward'></a>
4021 ## `slicesbackward`: replace backward loops over slices with slices.Backward
4022
4023 The slicesbackward analyzer suggests replacing manually-written backward loops of the form
4024
4025 for i := len(s) - 1; i >= 0; i-- {
4026 use(s[i])
4027 }
4028
4029 with the more readable Go 1.23 style using slices.Backward:
4030
4031 for _, v := range slices.Backward(s) {
4032 use(v)
4033 }
4034
4035 If the loop index is needed beyond just indexing into the slice, both the index and value variables are kept:
4036
4037 for i, v := range slices.Backward(s) { ... }
4038
4039
4040 Default: on.
4041
4042 Package documentation: [slicesbackward](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#slicesbackward)
4043
4044 <a id='slicescontains'></a>
4045 ## `slicescontains`: replace loops with slices.Contains or slices.ContainsFunc
4046
4047 The slicescontains analyzer simplifies loops that check for the existence of an element in a slice. It replaces them with calls to \`slices.Contains\` or \`slices.ContainsFunc\`, which were added in Go 1.21.
4048
4049 If the expression for the target element has side effects, this transformation will cause those effects to occur only once, not once per tested slice element.
4050
4051
4052 Default: on.
4053
4054 Package documentation: [slicescontains](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#slicescontains)
4055
4056 <a id='slicesdelete'></a>
4057 ## `slicesdelete`: replace append-based slice deletion with slices.Delete
4058
4059 The slicesdelete analyzer suggests replacing the idiom
4060
4061 s = append(s[:i], s[j:]...)
4062
4063 with the more explicit
4064
4065 s = slices.Delete(s, i, j)
4066
4067 introduced in Go 1.21.
4068
4069 This analyzer is disabled by default. The \`slices.Delete\` function zeros the elements between the new length and the old length of the slice to prevent memory leaks, which is a subtle difference in behavior compared to the append-based idiom; see [https://go.dev/issue/73686](https://go.dev/issue/73686).
4070
4071
4072 Default: off. Enable by setting `"analyses": {"slicesdelete": true}`.
4073
4074 Package documentation: [slicesdelete](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#slicesdelete)
4075
4076 <a id='slicessort'></a>
4077 ## `slicessort`: replace sort.Slice with slices.Sort for basic types
4078
4079 The slicessort analyzer simplifies sorting slices of basic ordered types. It replaces
4080
4081 sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
4082
4083 with the simpler \`slices.Sort(s)\`, which was added in Go 1.21.
4084
4085
4086 Default: on.
4087
4088 Package documentation: [slicessort](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#slicessort)
4089
4090 <a id='slog'></a>
4091 ## `slog`: check for invalid structured logging calls
4092
4093 The slog checker looks for calls to functions from the log/slog package that take alternating key-value pairs. It reports calls where an argument in a key position is neither a string nor a slog.Attr, and where a final key is missing its value. For example,it would report
4094
4095 slog.Warn("message", 11, "k") // slog.Warn arg "11" should be a string or a slog.Attr
4096
4097 and
4098
4099 slog.Info("message", "k1", v1, "k2") // call to slog.Info missing a final value
4100
4101
4102 Default: on.
4103
4104 Package documentation: [slog](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/slog)
4105
4106 <a id='sortslice'></a>
4107 ## `sortslice`: check the argument type of sort.Slice
4108
4109 sort.Slice requires an argument of a slice type. Check that the interface{} value passed to sort.Slice is actually a slice.
4110
4111
4112 Default: on.
4113
4114 Package documentation: [sortslice](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/sortslice)
4115
4116 <a id='sqlrowserr'></a>
4117 ## `sqlrowserr`: report failure to check sql.Rows.Err
4118
4119 This analyzer reports uses of sql.Rows in which the result of a query such as db.Query() is assigned to a local variable that is then used in a loop that calls Rows.Next, but lacks a final check of Rows.Err. This causes row iteration errors to be discarded.
4120
4121 For example:
4122
4123 rows, err := db.Query("select ...") // error: "sql.Rows rows is used in Next loop without final check of rows.Err()"
4124 if err != nil {
4125 return err
4126 }
4127 defer rows.Close() // ignore error
4128 for rows.Next() {
4129 var x int
4130 if err := rows.Scan(&x); err != nil {
4131 return err
4132 }
4133 use(x)
4134 }
4135 /* ...no use of rows.Err()... */
4136
4137 Correct usage of sql.Rows demands both a call to Rows.Close to release resources and a call to Rows.Err to report iteration errors. It is not critical to report resource cleanup errors, but it is crucial to report iteration errors as they would otherwise be indistinguishable from a smaller result.
4138
4139 To avoid false positives, the analyzer is silent if the Rows is passed into or out of the function or assigned somewhere other than a local variable.
4140
4141 It is not this analyzer's goal to ensure proper handling of errors in all cases, but merely the simple mistakes where the user may have been oblivious to the existence of the Rows.Err method.
4142
4143
4144 Default: on.
4145
4146 Package documentation: [sqlrowserr](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/sqlrowserr)
4147
4148 <a id='stditerators'></a>
4149 ## `stditerators`: use iterators instead of Len/At-style APIs
4150
4151 This analyzer suggests a fix to replace each loop of the form:
4152
4153 for i := 0; i < x.Len(); i++ {
4154 use(x.At(i))
4155 }
4156
4157 or its "for elem := range x.Len()" equivalent by a range loop over an iterator offered by the same data type:
4158
4159 for elem := range x.All() {
4160 use(x.At(i)
4161 }
4162
4163 where x is one of various well-known types in the standard library.
4164
4165
4166 Default: on.
4167
4168 Package documentation: [stditerators](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#stditerators)
4169
4170 <a id='stdmethods'></a>
4171 ## `stdmethods`: check signature of methods of well-known interfaces
4172
4173 Sometimes a type may be intended to satisfy an interface but may fail to do so because of a mistake in its method signature. For example, the result of this WriteTo method should be (int64, error), not error, to satisfy io.WriterTo:
4174
4175 type myWriterTo struct{...}
4176 func (myWriterTo) WriteTo(w io.Writer) error { ... }
4177
4178 This check ensures that each method whose name matches one of several well-known interface methods from the standard library has the correct signature for that interface.
4179
4180 Checked method names include:
4181
4182 Format GobEncode GobDecode MarshalJSON MarshalXML
4183 Peek ReadByte ReadFrom ReadRune Scan Seek
4184 UnmarshalJSON UnreadByte UnreadRune WriteByte
4185 WriteTo
4186
4187
4188 Default: on.
4189
4190 Package documentation: [stdmethods](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/stdmethods)
4191
4192 <a id='stdversion'></a>
4193 ## `stdversion`: report uses of too-new standard library symbols
4194
4195 The stdversion analyzer reports references to symbols in the standard library that were introduced by a Go release higher than the one in force in the referring file. (Recall that the file's Go version is defined by the 'go' directive its module's go.mod file, or by a "//go:build go1.X" build tag at the top of the file.)
4196
4197 The analyzer does not report a diagnostic for a reference to a "too new" field or method of a type that is itself "too new", as this may have false positives, for example if fields or methods are accessed through a type alias that is guarded by a Go version constraint.
4198
4199
4200 Default: on.
4201
4202 Package documentation: [stdversion](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/stdversion)
4203
4204 <a id='stringintconv'></a>
4205 ## `stringintconv`: check for string(int) conversions
4206
4207 This checker flags conversions of the form string(x) where x is an integer (but not byte or rune) type. Such conversions are discouraged because they return the UTF-8 representation of the Unicode code point x, and not a decimal string representation of x as one might expect. Furthermore, if x denotes an invalid code point, the conversion cannot be statically rejected.
4208
4209 For conversions that intend on using the code point, consider replacing them with string(rune(x)). Otherwise, strconv.Itoa and its equivalents return the string representation of the value in the desired base.
4210
4211
4212 Default: on.
4213
4214 Package documentation: [stringintconv](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/stringintconv)
4215
4216 <a id='stringsbuilder'></a>
4217 ## `stringsbuilder`: replace += with strings.Builder
4218
4219 This analyzer replaces repeated string += string concatenation operations with calls to Go 1.10's strings.Builder.
4220
4221 For example:
4222
4223 var s = "["
4224 for x := range seq {
4225 s += x
4226 s += "."
4227 }
4228 s += "]"
4229 use(s)
4230
4231 is replaced by:
4232
4233 var s strings.Builder
4234 s.WriteString("[")
4235 for x := range seq {
4236 s.WriteString(x)
4237 s.WriteString(".")
4238 }
4239 s.WriteString("]")
4240 use(s.String())
4241
4242 This avoids quadratic memory allocation and improves performance.
4243
4244 No diagnostics are issued in tests, where data sizes are often small and asymptotic performance is not a security concern.
4245
4246 The analyzer requires that all references to s before the final uses are += operations. To avoid warning about trivial cases, at least one must appear within a loop. The variable s must be a local variable, not a global or parameter.
4247
4248 All uses of the finished string must come after the last += operation. Each such use will be replaced by a call to strings.Builder's String method. (These may appear within an intervening loop or function literal, since even if s.String() is called repeatedly, it does not allocate memory.)
4249
4250 Often the addend is a call to fmt.Sprintf, as in this example:
4251
4252 var s string
4253 for x := range seq {
4254 s += fmt.Sprintf("%v", x)
4255 }
4256
4257 which, once the suggested fix is applied, becomes:
4258
4259 var s strings.Builder
4260 for x := range seq {
4261 s.WriteString(fmt.Sprintf("%v", x))
4262 }
4263
4264 The WriteString call can be further simplified to the more efficient fmt.Fprintf(&s, "%v", x), avoiding the allocation of an intermediary. However, stringsbuilder does not perform this simplification; it requires staticcheck analyzer QF1012. (See [https://go.dev/issue/76918](https://go.dev/issue/76918).)
4265
4266
4267 Default: on.
4268
4269 Package documentation: [stringsbuilder](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#stringbuilder)
4270
4271 <a id='stringscut'></a>
4272 ## `stringscut`: replace strings.Index etc. with strings.Cut
4273
4274 This analyzer replaces certain patterns of use of [strings.Index](/strings#Index) and string slicing by [strings.Cut](/strings#Cut), added in go1.18.
4275
4276 For example:
4277
4278 idx := strings.Index(s, substr)
4279 if idx >= 0 {
4280 return s[:idx]
4281 }
4282
4283 is replaced by:
4284
4285 before, _, ok := strings.Cut(s, substr)
4286 if ok {
4287 return before
4288 }
4289
4290 And:
4291
4292 idx := strings.Index(s, substr)
4293 if idx >= 0 {
4294 return
4295 }
4296
4297 is replaced by:
4298
4299 found := strings.Contains(s, substr)
4300 if found {
4301 return
4302 }
4303
4304 It also handles variants using [strings.IndexByte](/strings#IndexByte) instead of Index, or the bytes package instead of strings.
4305
4306 Fixes are offered only in cases in which there are no potential modifications of the idx, s, or substr expressions between their definition and use.
4307
4308 It also replaces [strings.SplitN](/strings#SplitN)(s, sep, 2)\[0] and [strings.Split](/strings#Split)(s, sep)\[0] with the "before" result of strings.Cut, when sep is a non-empty string constant:
4309
4310 x := strings.SplitN(s, sep, 2)[0]
4311
4312 is replaced by:
4313
4314 x, _, _ := strings.Cut(s, sep)
4315
4316 The fix is only offered when sep is a non-empty string literal. When sep is a variable or the empty string, the semantics differ (strings.Split(s, "")\[0] returns the first character of s, but strings.Cut(s, "").before is ""), so no fix is suggested.
4317
4318
4319 Default: on.
4320
4321 Package documentation: [stringscut](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#stringscut)
4322
4323 <a id='stringscutprefix'></a>
4324 ## `stringscutprefix`: replace HasPrefix/TrimPrefix with CutPrefix
4325
4326 The stringscutprefix analyzer simplifies a common pattern where code first checks for a prefix with \`strings.HasPrefix\` and then removes it with \`strings.TrimPrefix\`. It replaces this two-step process with a single call to \`strings.CutPrefix\`, introduced in Go 1.20. The analyzer also handles the equivalent functions in the \`bytes\` package.
4327
4328 For example, this input:
4329
4330 if strings.HasPrefix(s, prefix) {
4331 use(strings.TrimPrefix(s, prefix))
4332 }
4333
4334 is fixed to:
4335
4336 if after, ok := strings.CutPrefix(s, prefix); ok {
4337 use(after)
4338 }
4339
4340 The analyzer also offers fixes to use CutSuffix in a similar way. This input:
4341
4342 if strings.HasSuffix(s, suffix) {
4343 use(strings.TrimSuffix(s, suffix))
4344 }
4345
4346 is fixed to:
4347
4348 if before, ok := strings.CutSuffix(s, suffix); ok {
4349 use(before)
4350 }
4351
4352
4353 Default: on.
4354
4355 Package documentation: [stringscutprefix](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#stringscutprefix)
4356
4357 <a id='stringsseq'></a>
4358 ## `stringsseq`: replace ranging over Split/Fields with SplitSeq/FieldsSeq
4359
4360 The stringsseq analyzer improves the efficiency of iterating over substrings. It replaces
4361
4362 for range strings.Split(...)
4363
4364 with the more efficient
4365
4366 for range strings.SplitSeq(...)
4367
4368 which was added in Go 1.24 and avoids allocating a slice for the substrings. The analyzer also handles strings.Fields and the equivalent functions in the bytes package.
4369
4370
4371 Default: on.
4372
4373 Package documentation: [stringsseq](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#stringsseq)
4374
4375 <a id='structtag'></a>
4376 ## `structtag`: check that struct field tags conform to reflect.StructTag.Get
4377
4378 Also report certain struct tags (json, xml) used with unexported fields.
4379
4380
4381 Default: on.
4382
4383 Package documentation: [structtag](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/structtag)
4384
4385 <a id='testingcontext'></a>
4386 ## `testingcontext`: replace context.WithCancel with t.Context in tests
4387
4388 The testingcontext analyzer simplifies context management in tests. It replaces the manual creation of a cancellable context,
4389
4390 ctx, cancel := context.WithCancel(context.Background())
4391 defer cancel()
4392
4393 with a single call to t.Context(), which was added in Go 1.24.
4394
4395 This change is only suggested if the \`cancel\` function is not used for any other purpose.
4396
4397
4398 Default: on.
4399
4400 Package documentation: [testingcontext](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#testingcontext)
4401
4402 <a id='testinggoroutine'></a>
4403 ## `testinggoroutine`: report calls to (*testing.T).Fatal from goroutines started by a test
4404
4405 Functions that abruptly terminate a test, such as the Fatal, Fatalf, FailNow, and Skip{,f,Now} methods of \*testing.T, must be called from the test goroutine itself. This checker detects calls to these functions that occur within a goroutine started by the test. For example:
4406
4407 func TestFoo(t *testing.T) {
4408 go func() {
4409 t.Fatal("oops") // error: (*T).Fatal called from non-test goroutine
4410 }()
4411 }
4412
4413
4414 Default: on.
4415
4416 Package documentation: [testinggoroutine](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/testinggoroutine)
4417
4418 <a id='tests'></a>
4419 ## `tests`: check for common mistaken usages of tests and examples
4420
4421 The tests checker walks Test, Benchmark, Fuzzing and Example functions checking malformed names, wrong signatures and examples documenting non-existent identifiers.
4422
4423 Please see the documentation for package testing in golang.org/pkg/testing for the conventions that are enforced for Tests, Benchmarks, and Examples.
4424
4425
4426 Default: on.
4427
4428 Package documentation: [tests](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/tests)
4429
4430 <a id='timeformat'></a>
4431 ## `timeformat`: check for calls of (time.Time).Format or time.Parse with 2006-02-01
4432
4433 The timeformat checker looks for time formats with the 2006-02-01 (yyyy-dd-mm) format. Internationally, "yyyy-dd-mm" does not occur in common calendar date standards, and so it is more likely that 2006-01-02 (yyyy-mm-dd) was intended.
4434
4435
4436 Default: on.
4437
4438 Package documentation: [timeformat](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/timeformat)
4439
4440 <a id='unmarshal'></a>
4441 ## `unmarshal`: report passing non-pointer or non-interface values to unmarshal
4442
4443 The unmarshal analysis reports calls to functions such as json.Unmarshal in which the argument type is not a pointer or an interface.
4444
4445
4446 Default: on.
4447
4448 Package documentation: [unmarshal](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/unmarshal)
4449
4450 <a id='unreachable'></a>
4451 ## `unreachable`: check for unreachable code
4452
4453 The unreachable analyzer finds statements that execution can never reach because they are preceded by a return statement, a call to panic, an infinite loop, or similar constructs.
4454
4455
4456 Default: on.
4457
4458 Package documentation: [unreachable](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/unreachable)
4459
4460 <a id='unsafefuncs'></a>
4461 ## `unsafefuncs`: replace unsafe pointer arithmetic with function calls
4462
4463 The unsafefuncs analyzer simplifies pointer arithmetic expressions by replacing them with calls to helper functions such as unsafe.Add, added in Go 1.17.
4464
4465 Example:
4466
4467 unsafe.Pointer(uintptr(ptr) + uintptr(n))
4468
4469 where ptr is an unsafe.Pointer, is replaced by:
4470
4471 unsafe.Add(ptr, n)
4472
4473
4474 Default: on.
4475
4476 Package documentation: [unsafefuncs](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#unsafefuncs)
4477
4478 <a id='unsafeptr'></a>
4479 ## `unsafeptr`: check for invalid conversions of uintptr to unsafe.Pointer
4480
4481 The unsafeptr analyzer reports likely incorrect uses of unsafe.Pointer to convert integers to pointers. A conversion from uintptr to unsafe.Pointer is invalid if it implies that there is a uintptr-typed word in memory that holds a pointer value, because that word will be invisible to stack copying and to the garbage collector.
4482
4483
4484 Default: on.
4485
4486 Package documentation: [unsafeptr](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/unsafeptr)
4487
4488 <a id='unusedfunc'></a>
4489 ## `unusedfunc`: check for unused functions, methods, etc
4490
4491 The unusedfunc analyzer reports functions and methods that are never referenced outside of their own declaration.
4492
4493 A function is considered unused if it is unexported and not referenced (except within its own declaration).
4494
4495 A method is considered unused if it is unexported, not referenced (except within its own declaration), and its name does not match that of any method of an interface type declared within the same package.
4496
4497 The tool may report false positives in some situations, for example:
4498
4499 - for a declaration of an unexported function that is referenced from another package using the go:linkname mechanism, if the declaration's doc comment does not also have a go:linkname comment.
4500
4501 (Such code is in any case strongly discouraged: linkname annotations, if they must be used at all, should be used on both the declaration and the alias.)
4502
4503 - for compiler intrinsics in the "runtime" package that, though never referenced, are known to the compiler and are called indirectly by compiled object code.
4504
4505 - for functions called only from assembly.
4506
4507 - for functions called only from files whose build tags are not selected in the current build configuration.
4508
4509 Since these situations are relatively common in the low-level parts of the runtime, this analyzer ignores the standard library. See [https://go.dev/issue/71686](https://go.dev/issue/71686) and [https://go.dev/issue/74130](https://go.dev/issue/74130) for further discussion of these limitations.
4510
4511 The unusedfunc algorithm is not as precise as the golang.org/x/tools/cmd/deadcode tool, but it has the advantage that it runs within the modular analysis framework, enabling near real-time feedback within gopls.
4512
4513 The unusedfunc analyzer also reports unused types, vars, and constants. Enums--constants defined with iota--are ignored since even the unused values must remain present to preserve the logical ordering.
4514
4515
4516 Default: on.
4517
4518 Package documentation: [unusedfunc](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/unusedfunc)
4519
4520 <a id='unusedparams'></a>
4521 ## `unusedparams`: check for unused parameters of functions
4522
4523 The unusedparams analyzer checks functions to see if there are any parameters that are not being used.
4524
4525 To ensure soundness, it ignores:
4526
4527 - "address-taken" functions, that is, functions that are used as a value rather than being called directly; their signatures may be required to conform to a func type.
4528 - exported functions or methods, since they may be address-taken in another package.
4529 - unexported methods whose name matches an interface method declared in the same package, since the method's signature may be required to conform to the interface type.
4530 - functions with empty bodies, or containing just a call to panic.
4531 - parameters that are unnamed, or named "\_", the blank identifier.
4532
4533 The analyzer suggests a fix of replacing the parameter name by "\_", but in such cases a deeper fix can be obtained by invoking the "Refactor: remove unused parameter" code action, which will eliminate the parameter entirely, along with all corresponding arguments at call sites, while taking care to preserve any side effects in the argument expressions; see [https://github.com/golang/tools/releases/tag/gopls%2Fv0.14](https://github.com/golang/tools/releases/tag/gopls%2Fv0.14).
4534
4535 This analyzer ignores generated code.
4536
4537
4538 Default: on.
4539
4540 Package documentation: [unusedparams](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/unusedparams)
4541
4542 <a id='unusedresult'></a>
4543 ## `unusedresult`: check for unused results of calls to some functions
4544
4545 Some functions like fmt.Errorf return a result and have no side effects, so it is always a mistake to discard the result. Other functions may return an error that must not be ignored, or a cleanup operation that must be called. This analyzer reports calls to functions like these when the result of the call is ignored.
4546
4547 The set of functions may be controlled using flags.
4548
4549
4550 Default: on.
4551
4552 Package documentation: [unusedresult](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/unusedresult)
4553
4554 <a id='unusedvariable'></a>
4555 ## `unusedvariable`: check for unused variables and suggest fixes
4556
4557
4558
4559 Default: on.
4560
4561 Package documentation: [unusedvariable](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/unusedvariable)
4562
4563 <a id='unusedwrite'></a>
4564 ## `unusedwrite`: checks for unused writes
4565
4566 The analyzer reports instances of writes to struct fields and arrays that are never read. Specifically, when a struct object or an array is copied, its elements are copied implicitly by the compiler, and any element write to this copy does nothing with the original object.
4567
4568 For example:
4569
4570 type T struct { x int }
4571
4572 func f(input []T) {
4573 for i, v := range input { // v is a copy
4574 v.x = i // unused write to field x
4575 }
4576 }
4577
4578 Another example is about non-pointer receiver:
4579
4580 type T struct { x int }
4581
4582 func (t T) f() { // t is a copy
4583 t.x = i // unused write to field x
4584 }
4585
4586
4587 Default: on.
4588
4589 Package documentation: [unusedwrite](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/unusedwrite)
4590
4591 <a id='waitgroup'></a>
4592 ## `waitgroup`: check for misuses of sync.WaitGroup
4593
4594 This analyzer detects mistaken calls to the (\*sync.WaitGroup).Add method from inside a new goroutine, causing Add to race with Wait:
4595
4596 // WRONG
4597 var wg sync.WaitGroup
4598 go func() {
4599 wg.Add(1) // "WaitGroup.Add called from inside new goroutine"
4600 defer wg.Done()
4601 ...
4602 }()
4603 wg.Wait() // (may return prematurely before new goroutine starts)
4604
4605 The correct code calls Add before starting the goroutine:
4606
4607 // RIGHT
4608 var wg sync.WaitGroup
4609 wg.Add(1)
4610 go func() {
4611 defer wg.Done()
4612 ...
4613 }()
4614 wg.Wait()
4615
4616
4617 Default: on.
4618
4619 Package documentation: [waitgroup](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/waitgroup)
4620
4621 <a id='waitgroupgo'></a>
4622 ## `waitgroupgo`: replace wg.Add(1)/go/wg.Done() with wg.Go
4623
4624 The waitgroupgo analyzer simplifies goroutine management with \`sync.WaitGroup\`. It replaces the common pattern
4625
4626 wg.Add(1)
4627 go func() {
4628 defer wg.Done()
4629 ...
4630 }()
4631
4632 with a single call to
4633
4634 wg.Go(func(){ ... })
4635
4636 which was added in Go 1.25.
4637
4638
4639 Default: on.
4640
4641 Package documentation: [waitgroupgo](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#waitgroupgo)
4642
4643 <a id='writestring'></a>
4644 ## `writestring`: detect inefficient string concatenation in uses of WriteString
4645
4646 The writestring analyzer offers to replace a call to WriteString(x + y) by two calls WriteString(x); WriteString(y). This is more efficient because it avoids the additional memory allocation produced by string concatenation; instead we just write each string into the buffer directly.
4647
4648 It explicitly looks for calls to certain well-known writers such as bytes.Buffer, strings.Builder and bufio.Writer. The analyzer will not suggest a fix for calls to, say, (\*os.File).WriteString, because for certain kinds of file such as a UDP socket, it could split a single message into two. Similarly it does not offer fixes when the type of the writer is unknown (as in calls to io.WriteString).
4649
4650 For example:
4651
4652 func f(a string, b string) string {
4653 var s strings.Builder
4654 s.WriteString(a+b)
4655 return s.String()
4656 }
4657
4658 would become:
4659
4660 func f(a string, b string) string {
4661 var s strings.Builder
4662 s.WriteString(a)
4663 s.WriteString(b)
4664 return s.String()
4665 }
4666
4667
4668 Default: on.
4669
4670 Package documentation: [writestring](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/writestring)
4671
4672 <a id='yield'></a>
4673 ## `yield`: report calls to yield where the result is ignored
4674
4675 After a yield function returns false, the caller should not call the yield function again; generally the iterator should return promptly.
4676
4677 This example fails to check the result of the call to yield, causing this analyzer to report a diagnostic:
4678
4679 yield(1) // yield may be called again (on L2) after returning false
4680 yield(2)
4681
4682 The corrected code is either this:
4683
4684 if yield(1) { yield(2) }
4685
4686 or simply:
4687
4688 _ = yield(1) && yield(2)
4689
4690 It is not always a mistake to ignore the result of yield. For example, this is a valid single-element iterator:
4691
4692 yield(1) // ok to ignore result
4693 return
4694
4695 It is only a mistake when the yield call that returned false may be followed by another call.
4696
4697
4698 Default: on.
4699
4700 Package documentation: [yield](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/yield)
4701
4702 <!-- END Analyzers: DO NOT MANUALLY EDIT THIS SECTION -->