I think this is somewhat standard behavior. In other programming languages, the compiler, or latest, the runtime might try to prevent modifications to a looped-over collection. Go would allow that when using a pointer. Makes sense from a semantic point of view. Treat the ranged-over slice as immutable, unless you use a pointer to it.
BTW, for the such and similar situations go-critic has checks
rangeValCopy
andrangeExprCopy
See docs: https://go-critic.github.io/overview
Repo: https://github.com/go-critic/go-critic
Thanks, I integrated it into my codebase. The default sizeLimit of 512 seems rather large, I would expect to see something like 64.
https://github.com/contribsys/faktory/blob/master/.golangci.yml
go-critic has a support for config per checker, look for
@rangeExprCopy.sizeThreshold
on the overview page :)And from what I see there is no mention of go-critic config param (oops), we’ll update docs soon.
Yeah, I dug thru it and config’d golangci-lint. See link above.
Just in case if you didn’t know: you can change the default size with
-@rangeExprCopy.sizeThreshold
parameter.To get a list of checkers, run:
gocritic doc
.To get info about a checker, run:
gocritic doc <checkerName>
.So, in case of the rangeExprCopy you do “gocritic doc rangeExprCopy” and it tells what parameters are available.
I think this is somewhat standard behavior. In other programming languages, the compiler, or latest, the runtime might try to prevent modifications to a looped-over collection. Go would allow that when using a pointer. Makes sense from a semantic point of view. Treat the ranged-over slice as immutable, unless you use a pointer to it.