• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

.circleci/H05-Dec-2020-1412

examples/H03-May-2022-107

makezero/H05-Dec-2020-301255

.golangci.ymlH A D05-Dec-202028 32

.pre-commit-config.yamlH A D05-Dec-2020113 65

LICENSEH A D05-Dec-2020561 1410

MakefileH A D05-Dec-2020119 53

README.mdH A D05-Dec-20202 KiB6543

go.modH A D05-Dec-2020151 96

go.sumH A D05-Dec-20202.4 KiB2726

main.goH A D05-Dec-20201.2 KiB5343

README.md

1# makezero
2
3makezero is a Go static analysis tool to find slice declarations that are not initialized with zero length and are later
4used with append.
5
6## Installation
7
8    go get -u github.com/ashanbrown/makezero
9
10## Usage
11
12Similar to other Go static analysis tools (such as golint, go vet), makezero can be invoked with one or more filenames, directories, or packages named by its import path. makezero also supports the `...` wildcard.
13
14    makezero [-always] packages...
15
16### Flags
17- **-set_exit_status** (default false) - Set exit status to 1 if any issues are found.
18- **-always** (default false) - Always require slices to be initialized with zero length, regardless of whether they are used with append.
19
20## Purpose
21
22To prevent bugs caused by initializing a slice with non-constant length and later appending to it.  The recommended
23[prealloc](https://github.com/alexkohler/prealloc) linter wisely encourages the developer to pre-allocate, but when we preallocate a slice with empty values in it and later append to it, we can easily introduce extra empty element in that slice.
24
25Consider the case below:
26
27```Go
28func copyNumbers(nums []int) []int {
29  values := make([]int, len(num)) // satisfy prealloc
30  for _, n := range nums {
31    values = apppend(values, n)
32  }
33  return values
34}
35```
36
37In this case, you probably mean to preallocate with length 0 `values := make([]int, 0, len(num))`.
38
39The `-always` directive enforces that slice created with `make` always have initial length of zero.  This may sound
40draconian but it encourages the use of `append` when building up arrays rather than C-style code featuring the index
41variable `i` such as in:
42
43```Go
44func copyNumbers(nums []int) []int {
45  values := make([]int, len(num))
46  for i, n := range nums {
47    values[i] = n
48  }
49  return values
50}
51
52```
53
54## Ignoring issues
55
56You can ignore a particular issue by including the directive `// nozero` on that line
57
58## TODO
59
60Consider whether this should be part of prealloc itself.
61
62## Contributing
63
64Pull requests welcome!
65