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

Does range operator really copy the iterable? #24

Closed
lootek opened this issue Apr 17, 2023 · 1 comment
Closed

Does range operator really copy the iterable? #24

lootek opened this issue Apr 17, 2023 · 1 comment

Comments

@lootek
Copy link

lootek commented Apr 17, 2023

Hello, first of all, please accept many thanks for the great book you wrote! It's awesome to have all those gotchas collected in one place and so well explained :)

I would like to ask for a further explanation of the statement in the book that made me a bit confused though. It says that the range operator copies the slice/array/channel being iterated over (ie the range clause) on its first (and only) evaluation just before the iteration. I cannot find that in the relevant part of the Golang spec. My understanding was, on the other hand, the for-range behaves that way because it's the v (the local iterator variable) that is a copy of the slice element (not that the whole iterable thing gets copied). Please see the following snippet: https://go.dev/play/p/tEE8fW6Jxrk.

Referring to the code samples in this repo here, such a statement can be found in the book as the comment eg. to this one (or a couple of other snippets in the 4.2.x chapter):

func listing1() {
a := [3]int{0, 1, 2}
for i, v := range a {
a[2] = 10
if i == 2 {
fmt.Println(v)
}
}
}

@teivah
Copy link
Owner

teivah commented Sep 28, 2023

You are right; this could be better phrased. Thanks, it'll be updated in the next version.

@teivah teivah closed this as completed Sep 28, 2023
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