Arrays in Nim

In Nim, an array is a fixed-size sequence of elements of a specific type. Arrays are useful in some scenarios, but in typical Nim code, sequences are more common due to their dynamic nature.

import std/strformat

proc main() =
  # Here we create an array `a` that will hold exactly
  # 5 integers. The type of elements and length are both
  # part of the array's type. By default, an array is
  # zero-initialized, which for integers means 0s.
  var a: array[5, int]
  echo fmt"emp: {a}"

  # We can set a value at an index using the
  # array[index] = value syntax, and get a value with
  # array[index].
  a[4] = 100
  echo fmt"set: {a}"
  echo fmt"get: {a[4]}"

  # The len() procedure returns the length of an array.
  echo fmt"len: {len(a)}"

  # Use this syntax to declare and initialize an array
  # in one line.
  var b = [1, 2, 3, 4, 5]
  echo fmt"dcl: {b}"

  # In Nim, you can use array[0..4, int] to specify
  # the range of indices.
  var c: array[0..4, int] = [1, 2, 3, 4, 5]
  echo fmt"range: {c}"

  # You can also use array comprehension to initialize arrays
  var d = [i * 10 for i in 0..4]
  echo fmt"comp: {d}"

  # Array types are one-dimensional, but you can
  # compose types to build multi-dimensional data
  # structures.
  var twoD: array[2, array[3, int]]
  for i in 0..1:
    for j in 0..2:
      twoD[i][j] = i + j
  echo fmt"2d: {twoD}"

  # You can create and initialize multi-dimensional
  # arrays at once too.
  twoD = [
    [1, 2, 3],
    [4, 5, 6]
  ]
  echo fmt"2d: {twoD}"

main()

Note that arrays in Nim are displayed in the form [v1, v2, v3, ...] when printed with echo.

To run the program, save it as arrays.nim and use the Nim compiler:

$ nim c -r arrays.nim
emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
range: [1, 2, 3, 4, 5]
comp: [0, 10, 20, 30, 40]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [4, 5, 6]]

In this Nim version:

  1. We use array[5, int] to declare a fixed-size array of 5 integers.
  2. Nim uses zero-based indexing, similar to many other programming languages.
  3. The len() procedure is used to get the length of an array.
  4. Nim allows array initialization using array literals [1, 2, 3, 4, 5].
  5. Nim supports array comprehensions, which can be used for more complex initializations.
  6. Multi-dimensional arrays are created by nesting array types.
  7. The fmt string interpolation is used for formatting output strings.

Nim’s arrays are similar to those in many other languages, providing a fixed-size container for elements of the same type. However, for more flexible collections, Nim also offers sequences, which can grow or shrink as needed.