Skip to content

Iterators

Kōdo provides a built-in iterator protocol that lets you traverse collections using for-in loops. Lists, Maps, and Strings all support iteration.

The simplest way to iterate is with for-in:

let items: List<Int> = list_new()
list_push(items, 10)
list_push(items, 20)
list_push(items, 30)
for item in items {
print_int(item)
}

Output:

10
20
30

for-in on a List<Int> visits each element in order:

let items: List<Int> = list_new()
list_push(items, 10)
list_push(items, 20)
list_push(items, 30)
for item in items {
print_int(item)
}

for-in works with both List<Int> and List<String>.

for-in on a Map<Int, Int> iterates over the keys:

let scores: Map<Int, Int> = map_new()
map_insert(scores, 1, 95)
map_insert(scores, 2, 87)
for key in scores {
print_int(key)
}

You can also use map_contains_key and map_get for direct lookups:

if map_contains_key(scores, 1) {
print_int(map_get(scores, 1))
}

Under the hood, for-in desugars to the iterator protocol:

  1. Call .iter() on the collection to get an iterator handle
  2. Call advance() on the iterator — returns 1 if an element is available, 0 if exhausted
  3. Call value() on the iterator to get the current element
  4. Repeat until advance() returns 0
  5. Call free() on the iterator to clean up

You don’t normally need to use the protocol directly — for-in handles it automatically.

You can iterate over a range of integers using a while loop or by building a list:

let i: Int = 0
while i < 10 {
print_int(i)
i = i + 1
}