Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 36 ยท Basics and Types

Variables: let, var and const

Learn Nim's three ways to declare names (let, var, const), type inference, default values, scope, shadowing, tuple unpacking and naming rules, with C stand-ins.

A variable is a name for a value. Nim gives you three keywords for introducing names, and choosing the right one is one of the first habits to build: let for values that never change after being set, var for values that do change, and const for values the compiler can compute before your program even starts.

Nim snippets are read-only on this site (the compiler cannot run here). Runnable C stand-ins show the same ideas.

var: a variable that can change

NIM
var score = 0
score = 10
score += 5
echo score        # 15

The compiler infers score as an int from the value 0. You can also write the type yourself:

NIM
var ratio: float = 0.5
var name: string          # no value given: it starts as ""
var count: int            # starts as 0

Nim always initializes variables. If you give no value, you get the type's default: 0 for numbers, false for bool, "" for string, an empty seq, and nil for references. You never read garbage memory the way you can in C.

Several names can be declared in one statement:

NIM
var width, height = 100       # both are int, both 100
var x, y: float               # both float, both 0.0

You can also declare a block of variables:

NIM
var
  a = 1
  b = "text"
  c: bool

let: assigned once

NIM
let language = "Nim"
language = "C"        # compile error: 'language' cannot be assigned to

A let name is single-assignment. It must be given a value where it is declared, and it cannot be changed. The value can still be computed at run time:

NIM
import std/times
let started = now()   # not known until the program runs

Prefer let whenever you can. It makes code easier to read, because a reader knows the name will not change, and it lets the compiler optimize.

Start with let. Switch to var only when the compiler tells you that you assign twice.

const: known at compile time

NIM
const maxUsers = 100
const greeting = "Hello, " & "Nim"
const area = 3.14159 * 2.0 * 2.0

A const value must be computable at compile time: literals, arithmetic, and calls to most pure procedures. The compiler evaluates it once and puts the result straight into the program. Even a whole table can be built at compile time:

NIM
func squares(n: int): seq[int] =
  for i in 0 ..< n:
    result.add i * i

const table = squares(5)      # computed by the compiler
echo table                    # @[0, 1, 4, 9, 16]
Keyword Can change? Known when? Typical use
const no compile time limits, tables, configuration
let no run time results you keep around
var yes run time counters, accumulators, state
flowchart TD
  A{"Does the value<br/>change later?"} -- yes --> V["var"]
  A -- no --> B{"Computable before<br/>the program runs?"}
  B -- yes --> C["const"]
  B -- no --> L["let"]

Caption: a simple decision for choosing a declaration.

Type inference and annotations

Nim infers types for variables from their initial value. This does not make it dynamically typed: the type is fixed forever.

NIM
var n = 5
n = "five"        # error: type mismatch (int vs string)

Write the type when there is no value (var total: float), when you want a specific type (let small: int8 = 5), or for documentation. Number literals can carry a type suffix such as 5'u8 or 2.5'f32.

Scope and shadowing

A name lives from its declaration to the end of its block. Blocks are made by if, for, while, procedures and the explicit block statement:

NIM
let x = 1
block:
  let y = 2
  echo x + y        # 3
# y is gone here

Nim allows a nested scope to shadow an outer name, but you may not declare the same name twice in the same scope. Shadowing is legal, though often confusing; give names distinct meanings instead.

Tuple unpacking

Several names can be introduced at once from a tuple:

NIM
let (quotient, remainder) = (17 div 5, 17 mod 5)
echo quotient, " ", remainder      # 3 2

Tuples are explained in their own lesson.

Naming rules

An identifier starts with a letter and may contain letters, digits and single underscores (no leading or doubled underscores). Nim compares names ignoring case and underscores after the first character: userName, user_name and username are the same, while UserName is not, because the first letter differs. The convention is camelCase for variables and procedures, and PascalCase for types. The name of a variable that clashes with a keyword can be written in backticks, as in let `type` = 1.

Stand-in: defaults, const and scope in C

C does not zero-initialize local variables, so this stand-in does it by hand to show what Nim does for you. It also contrasts a compile-time constant with a run-time value, and a nested scope.

C Stand-in: zero defaults, const and block scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The const qualifier in C makes a name read-only like let. Nim's const is closer to a macro or constant expression, since the value must be known to the compiler.

A second stand-in: the compile-time table

Nim's const table = squares(5) computes the table while compiling. In C you would normally generate the table by hand or with a script. This stand-in computes it at run time, to show the same data.

C Stand-in: building the squares table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output matches what Nim prints for echo table, but in Nim the work happens before the program runs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which declaration is best for a value that is set once at run time and never changes?

    let is single-assignment and may use run-time values; const needs a compile-time value.
  2. 2. What is the value of var count: int before you assign anything?

    Nim zero-initializes variables to the type's default.
  3. 3. Which of these refer to the same Nim variable?

    After the first character, case and underscores are ignored, so userName and user_name match. The first letter is case-sensitive.
  4. 4. Which line fails to compile?

    A let name cannot be reassigned.

Summary

  • var can change, let is assigned once, const is fixed at compile time.
  • Variables are always initialized to the default of their type.
  • Types are inferred but static; annotate when there is no value or you need a specific type.
  • Scopes end with their block; names ignore case and underscores after the first letter.

Next: Numbers: integers and floats