Tuples are one of the features to declare a new type using existing data types.
When you have multiple values of different datatypes, that need to pass between different procedures and files, the Tuple type allows you to pack and unpack the multiple values.
How to declare tuple type in NIM
A tuple can be declared with a tuple keyword using fields and datatype.
In multiple ways, we can create a tuple The first way, using fieldname and datatype with a square bracket([]) The second way, using datatype ([])
Here is an example
var newtype: tuple[fields: datatype1, fields: datatype2 ...]
var newtype1: ( datatype1, datatype2 ...)
Here is an example for declaring a tuple
var
Employee : tuple[id: int, name: string] #named fields
AdminEmployee : (int, string) # without fields
Below are two ways to assign
Employee = (id: 1, name: "john")
AdminEmployee = (1, "john")
How to access the Tuple fields in Nim?
Nim fields can be accessed.
- using field names in case of field names
var
Employee : tuple[id: int, name: string] #named fields
Employee = (id: 1, name: "john")
echo Employee.id # 1
echo Employee.name # john
- Using index with square brackets([]) incase of without field names
var
AdminEmployee : (int, string) # without fields
AdminEmployee = (1, "john")
echo AdminEmployee[0] # 1
echo AdminEmployee[1] # john
Nim Tuple unpacking example
Tuples can be unpacked using variable extract syntax and assign to individual variables
Assign the Tuple to variables, You can ignore fields using Underscore(_) operator.
var
Employee : tuple[id: int, name: string] #named fields
AdminEmployee : (int, string) # without fields
Employee = (id: 1, name: "john")
AdminEmployee = (1, "john")
let (id,name)= Employee
let (_,name)= Employee