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

Preallocate slices demo snippet has a mistaken #7

Closed
barryz opened this issue Aug 28, 2018 · 2 comments
Closed

Preallocate slices demo snippet has a mistaken #7

barryz opened this issue Aug 28, 2018 · 2 comments

Comments

@barryz
Copy link

barryz commented Aug 28, 2018

Article: 6-tips-and-tricks/1-tips-and-tricks.md
Section: Preallocate slices if the length is known

Wrong demo:

vals := fn()
s := make([]string, len(vals))  // should pre-allocate the capacity of slice.
for i, v := range vals {
        s[i] = v
}
return s

Right demo:

vals := fn()
s := make([]string, 0, len(vals))  // should pre-allocate the capacity of slice.
for i, v := range vals {
        s[i] = v
}
return s
@quasilyte
Copy link

@barryz, the proposed "right" version will panic due to out-of-range access.

The capacity pre-allocation should be used with append without direct index assignment.
Initial demo does the length-based pre-allocation with index assignment.

See https://play.golang.org/p/b1T5JU6T2DQ

If you agree, this issue should be closed.

@barryz
Copy link
Author

barryz commented Aug 30, 2018

okay, i will close the issue.

@barryz barryz closed this as completed Aug 30, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants