Nim Tuple Iterator examples?

This short tutorial explains how to iterate tuple types in Nim Language.

How to Iterate Tuple Types in Nim

Let’s declare a tuple, tuple contains items enclosed in (). tuple.fields return the iterator for field values.

use for in loop to iterate each element.

The below example contains tuples without field names.

// tuple without field names
let t = (1,2,3,4,5)

for item in t.fields:
  echo(item)

Output:

1
2
3
4
5

The below example contains tuples without field names.

// tuple with field names
let employee = (name: "john", id: 1)

for item in employee.fields:
  echo(item)

Output:

john
1

How to iterate field name and value of a tuple object in Nim

tuple contains the key and value of fields.

This example gets each field and value of a tuple object in Nim tuple.fieldPairs returns an object of fieldName, fieldValue, use those variables for each iteration

let employee = (name: "john", id: 1)

for fieldName, fieldValue in employee.fieldPairs:
   echo fieldName," - ",fieldValue