Range Over Built in Nim

Range over Built-in Types in Nim

In this example, we iterate over elements in various built-in data structures using for loops.

Here we use for to sum the numbers in an array. Arrays and sequences work similarly in Nim.

import strutils

proc main() =
    var nums = @[2, 3, 4]
    var sum = 0
    for num in nums:
        sum += num
    echo "sum: ", sum
    
main()

for loops in Nim provide both the index and value for each entry. If the index isn’t needed, we can ignore it.

import strutils

proc main() =
    var nums = @[2, 3, 4]
    for i, num in nums:
        if num == 3:
            echo "index: ", i
    
main()

for loops in maps (dictionaries) iterate over key/value pairs.

import strutils

proc main() =
    var kvs = {"a": "apple", "b": "banana"}
    for k, v in kvs:
        echo k, " -> ", v
    
main()

for loops can also iterate over just the keys of a map.

import strutils

proc main() =
    var kvs = {"a": "apple", "b": "banana"}
    for k in kvs.keys:
        echo "key: ", k
    
main()

for loops in strings iterate over Unicode code points. The first value is the byte index of the rune, and the second the rune itself. See the section on strings and runes for more details.

import strutils

proc main() =
    for i, c in "go":
        echo i, " ", c.ord
    
main()

Running the translated code will produce the following output, showing the results of each operation:

sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

Now, let’s proceed to the next example about pointers.