Loops
V has only one looping keyword: for
, with several forms.
for
Array The for value in arr
form is used for going through elements of an array.
If an index is required, an alternative form for index, value in arr
can be used.
Note that the value is read-only. If you need to modify the array while looping, you need to declare the element as mutable:
When an identifier is just a single underscore, it is ignored.
for
Map The for key, value in map
form is used for going through elements of a map.
Either key or value can be ignored by using a single underscore as the identifier.
for
Range low..high
means an exclusive range, which represents all values from low
up to but not including high
.
for
Condition This form of the loop is similar to while
loops in other languages.
The loop will stop iterating once the boolean condition evaluates to false.
for
Bare The condition can be omitted, resulting in an infinite loop.
for
C Finally, there's the traditional C style for
loop.
It's safer than the while
form because with the latter it's easy to forget
to update the counter and get stuck in an infinite loop.
Here i
doesn't need to be declared with mut
since it's always going to be mutable by definition.
Break & continue
break
and continue
control the innermost for
loop.
break
terminates the innermostfor
loop.continue
skips the rest of the current iteration and proceeds to the next step of the nearest enclosing loop.
Labelled break & continue
break
and continue
control the innermost for
loop by default.
You can also use break
and continue
followed by a label name to refer to an outer for
loop:
The label must immediately precede the outer loop.
Custom iterators
Types that implement a next()
method returning an
Option
can be iterated with a for
loop.