Title here
Summary here
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:
array[5, int]
to declare a fixed-size array of 5 integers.len()
procedure is used to get the length of an array.[1, 2, 3, 4, 5]
.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.