Nim: Data Structures

Mar 21, 2022

More complex data structures can be defined via a type statement:

  State = enum
    Victoria, NewSouthWales, Queensland, Tasmania, SouthAustralia, NorthernTerritory, WesternAustralia, ACT

var home = Victoria

echo home
# Victoria

echo typeof home
# State

Arrays in Nim are of fixed length with their size specificed at compile time. Sequences are like arrays, but have a dynamic length. They can be constructed by the array constructor [] in conjunction with the array to sequence operator @.

  x: seq[int] # a reference to a sequence of integers
x = @[1, 2, 3, 4, 5, 6]

There's also openarrays, though they can only be used as parameters:

proc openArraySize(oa: openArray[string]): int =

Creating a custom object is done by defining a new type, with a type of object:

  Person = object
    name: string
    age: int

var person1 = Person(name: "Peter", age: 30)

echo # "Peter"
echo person1.age  # 30

Mark fields that should be visible from outside the defining module with *.

  Person* = object # the type is visible from other modules
    name*: string  # the field of this type is visible from other modules
    age*: int

A similar but alternate approach for object-like behaviour is to use tuples:

  Person = tuple[name: string, age: int]

  person: Person

person = (name: "Peter", age: 30)
Hi, I'm Glenn! 👋 I'm currently Director of Product (Terraform) @ HashiCorp, and we're hiring! If you'd like to come and work with me and help make Terraform Cloud even more amazing we have multiple positions opening in Product ManagementDesign, and Engineering & Engineering Management across a range of levels (i.e., junior through to senior). Please send in an application ASAP so we can get in touch.