You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
v3: for x in a[b.len..] evaluates the slice again on every iteration, so a body that changes b.len skips elements #32309
With the default (V3) compiler, in for x in a[b.len..] the slice is not taken once before the loop: the generated C evaluates array_slice(a, b.len, a.len) again in the loop condition and in the element access of every iteration. When the body changes what the start expression reads (here, it appends to b), the loop skips elements of a.
With a start held in a variable (start := b.len then a[start..]), and with -old-compiler, the loop sees every element. A start that is a function call (a[start()..]) is also evaluated once.
Reproduction Steps
fnmain() {
a:= [1, 2, 3]
mutb:= []int{}
for x in a[b.len..] {
b << x
}
println(b)
mutc:= []int{}
start:= c.len
for x in a[start..] {
c << x
}
println(c)
}
V_C_ERROR_BUG_REPORT_DISABLED=1 V_MACOS_V3_NO_FALLBACK=1 v run main.v
Expected Behavior
[1, 2, 3]
[1, 2, 3]
as with v -old-compiler run main.v: the range of a for … in is evaluated once, before the first iteration.
After the first iteration b.len is 1, so the slice is [2, 3] and index 1 reads 3; after the second, the slice [3] has length 1 and the loop ends.
Possible Solution
Hoist the sliced array into a temporary before the loop, as is already done when the start is a call.
Additional Information/Context
Found in a linter written in V, where a loop that merged option arrays this way (for option in options[merged.len..] { merged << option }) lost every other option. Taking the slice into a variable first works around it.
V version
V 0.5.2 ba41fa1 (master, 2026-11-13); also 8415951.
Environment details (OS name and version, etc.)
Linux x86_64 (Ubuntu, kernel 6.8), gcc.
Note
You can use the 👍 reaction to increase the issue's priority for developers.
Please note that only the 👍 reaction to the issue itself counts as a vote.
Other reactions and those to comments will not be taken into account.
Activity