about for range with array?

151 views
Skip to first unread message

xie cui

unread,
Dec 24, 2021, 12:08:23 PM12/24/21
to golang-nuts
in the lang spec, it says:
The range expression x is evaluated once before beginning the loop, with one exception: if at most one iteration variable is present and len(x) is constant, the range expression is not evaluated.


first range expr will be evaluated.

second range expr will not be evaluated.

third range expr will be evaluated.

is this correct?

and 

does the range expr will be evaluated means when range expr is slice, the slice header will be copy, and when range expr is array, array will be coy?

Kevin Chowski

unread,
Dec 24, 2021, 12:38:14 PM12/24/21
to golang-nuts
Comments inline below:

On Friday, December 24, 2021 at 10:08:23 AM UTC-7 cuiw...@gmail.com wrote:
in the lang spec, it says:
The range expression x is evaluated once before beginning the loop, with one exception: if at most one iteration variable is present and len(x) is constant, the range expression is not evaluated.



first range expr will be evaluated.

second range expr will not be evaluated.

third range expr will be evaluated.

is this correct?

Those three statements seem correct to me. The easiest way to check is to pass a nil array, which will panic if evaluated and not panic if not evaluated. For example: https://go.dev/play/p/P1DDtZKy2jj
 

and 

does the range expr will be evaluated means when range expr is slice, the slice header will be copy, and when range expr is array, array will be coy?

I believe this is true, but I don't quite know why it is guaranteed in the specification. Someone else may be able answer this question with more evidence.

 

Ian Lance Taylor

unread,
Dec 24, 2021, 12:48:11 PM12/24/21
to Kevin Chowski, golang-nuts
Yes, the slice header or the entire array will be copied when the loop
starts (at least conceptually copied--the compiler can eliminate the
actual copy if it doesn't make any difference). This clarifies what
happens if the range loop changes the slice or array during the loop.

Ian
Reply all
Reply to author
Forward
0 new messages