Skip to content

Nim Cheatsheet

Efficient, expressive systems language that compiles to C, C++, or JavaScript.

01

Getting Started

Hello World

echo is a built-in that prints to stdout with a newline.

nim
echo "Hello, World!"

Variables

var is mutable, let is immutable after assignment, const is compile-time constant.

nim
var x = 10
let y = 20
const z = 30
echo x + y + z

Procedures

Procedures use = for body assignment; last expression is returned.

nim
proc add(a, b: int): int =
  a + b

echo add(3, 4)

Compilation

nim c compiles to C, nim js compiles to JavaScript.

nim
# nim c -d:release main.nim
# nim js main.nim  (compile to JS)
02

Control Flow

If-Else

Indentation-based blocks, similar to Python.

nim
let n = 5
if n > 3:
  echo "big"
elif n == 3:
  echo "three"
else:
  echo "small"

Case

case/of for multi-way branching.

nim
let day = "Mon"
case day
of "Mon": echo "Monday"
of "Tue": echo "Tuesday"
else: echo "Other"

While Loop

inc is a built-in that increments in place.

nim
var i = 0
while i < 5:
  echo i
  inc i

For Loop

..< is exclusive range, .. is inclusive range.

nim
for i in 0..<5:
  echo i

for ch in "hello":
  echo ch
03

Data Structures

Sequences

@[] creates a seq (dynamic array).

nim
var nums = @[1, 2, 3]
nums.add(4)
nums.insert(0, 0)
echo nums.len

Strings

Strings are mutable; slicing with .. works.

nim
var s = "Hello"
s.add(" World")
echo s[0..4]
echo s.len

Tables

Tables are hash maps.

nim
import std/tables
var t = initTable[string, int]()
t["a"] = 1
t["b"] = 2
echo t["a"]

Tuples

Tuples support unpacking.

nim
let p = (10, 20)
echo p[0]
let (x, y) = p
echo x, y
04

Advanced

Templates

Templates are for metaprogramming — code expansion at compile time.

nim
template twice(body: untyped) =
  body
  body

twice:
  echo "repeated"

Macros

Macros operate on AST for powerful code generation.

nim
import std/macros
macro echoArgs(args: varargs[untyped]): untyped =
  result = newNimNode(nnkStmtList)
  for a in args:
    result.add quote do: echo `a`

echoArgs(1, 2, 3)

Exceptions

Exceptions use raise/except pattern.

nim
try:
  raise newException(ValueError, "bad")
except ValueError as e:
  echo e.msg

Was this helpful?