Variables in Nim

In Nim, variables are explicitly declared and used by the compiler to check type-correctness of function calls.

import strformat

proc main() =
  # var declares 1 or more variables.
  var a = "initial"
  echo a

  # You can declare multiple variables at once.
  var 
    b = 1
    c = 2
  echo fmt"{b} {c}"

  # Nim will infer the type of initialized variables.
  var d = true
  echo d

  # Variables declared without a corresponding
  # initialization are default-initialized. For example,
  # the default value for an int is 0.
  var e: int
  echo e

  # The `=` syntax is used for declaring and
  # initializing a variable. Nim doesn't have a special
  # shorthand syntax like := in other languages.
  let f = "apple"
  echo f

main()

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

$ nim c -r variables.nim
initial
1 2
true
0
apple

In Nim:

  1. Variables are declared using the var keyword.
  2. Multiple variables can be declared in a single var block.
  3. Nim has type inference, so you don’t always need to specify the type explicitly.
  4. Uninitialized variables are automatically initialized with default values.
  5. The let keyword is used for declaring constants (immutable variables).

Nim’s syntax is more similar to Python than C-like languages, but it maintains strong static typing and compile-time checks.