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

Cuddle assignments used inside a for block #81

Closed
sudhirj opened this issue Apr 29, 2020 · 2 comments
Closed

Cuddle assignments used inside a for block #81

sudhirj opened this issue Apr 29, 2020 · 2 comments

Comments

@sudhirj
Copy link

sudhirj commented Apr 29, 2020

Consider the following code which WSL currently demands under the rule of ranges should only be cuddled with assignments used in the iteration:

clauses := make([]string, len(b.clauses))
i := 0

for k, v := range b.clauses {
	clauses[i] = k + " " + strings.Join(v, ", ")
	i++
}

It seems to me that since the sole purpose of i is for the iteration, and it's being incremented inside the block, that the following would be better:

clauses := make([]string, len(b.clauses))

i := 0
for k, v := range b.clauses {
	clauses[i] = k + " " + strings.Join(v, ", ")
	i++
}

Do you think that variables initialized for the purposes of iterating over maps and incremented inside the for loop should be considered an "assignment used in the iteration"?

@bombsimon
Copy link
Owner

bombsimon commented Apr 29, 2020

Thanks for the report!

Yeah I guess i is a bit special, at least in this case. One way this would be solved would be if #24 got implemented, however that's not specific for the iteration or i case.

I guess an option to configure something like iteration variables could be added allowing you to cuddled any assignment with a for loop as long as it's in this list. Something like wsl --iteration-variables=i,j,k ./...?

I'm a bit curious though, according to this SO post, there is no difference in performance between append and assignment since Go v1.10.1. At least if you pre-allocate the size of the slice so it has the proper capacity. This post is old but has some benchmarks to look at and test in your preferred version.

Would this be an alternative in your case?

clauses := make([]string, 0, len(b.clauses)

for k, v := range b.clauses {
	clauses = append(clauses, k + " " + strings.Join(v, ", "))
}

@sudhirj
Copy link
Author

sudhirj commented Apr 30, 2020

Sorry, you're absolutely right. There's no reason for the iterator there. I didn't realize that make had the other form with with both a length and capacity argument.

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