Loops

Loops

while

let index = 0
while index < count {
    io::println(names[index])
    index = index + 1
}

The condition is a bool and the braces are required.

for

for iterates any value with an iter() method returning something whose next() yields an optional. There is no Iterable trait: being iterable means having that method.

let names = list_dir(path)
for name in names {
    recursive_remove(join_path(path, name))
}

The loop variable is bound fresh on each pass and is scoped to the body.

In the standard library only Array and List have iter(). Map, IndexMap, and string do not, so for k in map is a compile error; walk map.key_list() or map.entries() instead.

Iter also declares check(), but a for loop never calls it. It exists for driving an iterator by hand.

Destructuring in a for loop

When each element is a pair, the loop can unpack it directly:

for (key, value) in entries {
    io::println(`${key} = ${value}`)
}

This binds the element once and destructures it into the names, the same way let (a, b) = pair does, using the positional accessors.

Destructuring binds exactly two names and requires a Pair. Anything else reports that it cannot be destructured.

break and continue

while index < count {
    if names[index].size() == 0 {
        index = index + 1
        continue
    }
    if names[index] == target {
        break
    }
    index = index + 1
}

break leaves the innermost loop and continue starts its next pass. Note that continue skips the rest of the body, so a counter increment has to happen before it rather than at the bottom of the loop.