Nim Cheat Sheet
Practical Nim syntax covering variables, types, control flow, procedures, and sequences for a Python-like compiled language.
Basics
Variables and procedures.
# Variables and printinglet name = "World" # immutablevar counter = 0 # mutableecho "Hello, ", name, "!"echo "Value: ", counterproc add(a, b: int): int = a + b # implicit return of last expressionecho add(2, 3)
Types & Objects
Built-in types and a custom object type.
var x: int = 42var y: float = 3.14var s: string = "text"var flag: bool = truetype Point = object x, y: floatvar p = Point(x: 1.0, y: 2.0)echo p.x, " ", p.y
Control Flow
Conditionals and loops.
let n = 10if n > 5: echo "big"elif n == 5: echo "equal"else: echo "small"for i in 0..4: echo "i=", ivar count = 0while count < 3: inc count
Procs & Functions
Defining and annotating procedures.
- proc name(args): ReturnType = ...- Defines a procedure (function)
- func- Shorthand for a proc that has no side effects
- result- Implicit return variable, auto-returned at the end of a proc
- discard expr- Explicitly ignores a return value
- {.inline.}- Pragma requesting the compiler inline a proc
- proc greet(name: string = "World")- Declares a default parameter value
Collections
Sequences, arrays, and tables.
- @[1, 2, 3]- Sequence (dynamic array) literal
- [1, 2, 3]- Fixed-size array literal
- {"a": 1, "b": 2}.toTable- Creates a hash table
- seq[int]- Sequence type holding ints
- for x in mySeq: echo x- Iterates a sequence
- mySeq.add(4)- Appends an element to a sequence
Iterators & Yield
Custom iterators using yield for lazy sequences.
iterator countdown(n: int): int = var i = n while i > 0: yield i dec ifor x in countdown(3): echo x # 3 2 1# closure iterator (first-class)iterator pairs(): (int, string) {.closure.} = yield (1, "one") yield (2, "two")
Templates & Macros
Compile-time metaprogramming with templates and macros.
template `!=` (a, b: untyped): untyped = not (a == b)template benchmark(body: untyped) = let t0 = cpuTime() body echo "took ", cpuTime() - t0import macrosmacro debug(n: varargs[untyped]): untyped = result = newStmtList() for x in n: result.add newCall("echo", newLit(x.repr & " = "), x)
Memory & References
ref, ptr, and ARC/ORC memory management.
type Node = ref object # heap-allocated, GC'd value: int next: Nodevar n = Node(value: 1)n.next = Node(value: 2)# manual memory via ptr (unsafe)var p = create(int) # allocp[] = 42dealloc(p)# compile with --mm:orc for cycle collection
Error Handling
Exceptions, defer, and Option types.
- raise newException(ValueError, msg)- throw an exception with a message
- try/except/finally- catch exceptions; except ValueError as e for the object
- defer: stmt- run stmt when the current scope exits (cleanup)
- {.raises: [].}- pragma asserting a proc raises no exceptions
- import options; some(x) / none(int)- Option[T] for values that may be absent
- isSome / isNone / get()- inspect and unwrap an Option
Common Pragmas
Compiler directives attached to symbols.
- {.inline.}- hint the compiler to inline the proc
- {.discardable.}- allow ignoring the proc's return value
- {.deprecated.}- mark a symbol as deprecated with a warning
- {.async.}- mark a proc as asynchronous (needs asyncdispatch)
- {.exportc.} / {.importc.}- export to / import from C for FFI
- {.push checks: off.}- disable runtime checks for a block of code
Nim compiles to C and lets you drop into low-level control with pragmas or ptr types for hot loops, while keeping high-level, Python-like syntax everywhere else.