https://go.dev/ref/spec#Length_and_capacity says:
> The expression len(s) is constant if s is a string constant. The > expressions len(s) and cap(s) are constants if the type of s is an array or > pointer to an array and the expression s does not contain channel receives > or (non-constant) function calls; in this case s is not evaluated. > Otherwise, invocations of len and cap are not constant and s is evaluated. So, in your case, the array contains a function call, so `len(…)` is not constant. Here is a case where the clause from the spec makes an observable difference: https://go.dev/play/p/jeCk6vHzf9u Without that clause, the range loop would have to iterate over the element of the pointee, causing a nil-dereference panic. The clause allows this code to work. On Fri, Mar 18, 2022 at 12:43 PM Jochen Voss <jochen.v...@gmail.com> wrote: > Dear all, > > The spec at https://go.dev/ref/spec#For_range 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." > > What does the second half of this sentence mean? > > My guess was that this says that in "for i := range [3]int{1, 2, f()} ..." > the function f is not called, but I quick experiment shows that this guess > is wrong, see https://go.dev/play/p/MXqH_C7mllx . > > All the best, > Jochen > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/db6d865e-233e-4120-8ce5-5feb832732b6n%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/db6d865e-233e-4120-8ce5-5feb832732b6n%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAEkBMfG9FO_nVBoT9AXAkrGZE8FtSoWukeVW5OF%2B2P98VQHxRg%40mail.gmail.com.