Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Faulty prealloc #21

Open
cbndr opened this issue May 15, 2020 · 3 comments
Open

Faulty prealloc #21

cbndr opened this issue May 15, 2020 · 3 comments

Comments

@cbndr
Copy link

cbndr commented May 15, 2020

I currently work in a team and we had a code issue a few times that made it beyond code review.
It is pre-allocating a slice with size instead of cap, then use append on it. Example

ar := make([]int, 10)
for i:=0; i<10; i++ {
  ar = append(ar, i)
  }

The correct pre-alloc would be ar := make([]int, 0, 10). Because of the missing 0,, the faulty code produces an array of size 20.

Would it be possible to add a check for this into your linter? I could not find any linter that has this check.

@alexkohler
Copy link
Owner

Hi, thanks for reaching out. At first glance, it looks like it might be possible to add some sort of check for these types of errors. I'll try to take a closer look when I get a moment.

@cbndr
Copy link
Author

cbndr commented May 16, 2020

Thank you very much. I believe this mistake is quite common, especially due to the confusing pre-allocation of arrays vs maps in Golang. In arrays, the extra ,0 is needed to specify capacity, but not in maps.

@bunyk
Copy link

bunyk commented Sep 17, 2021

I recently found out that there is a linter for that: https://github.com/ashanbrown/makezero

That also has "Consider whether this should be part of prealloc itself." in TODO.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants