Getting Started
Hello World
echo is a built-in that prints to stdout with a newline.
echo "Hello, World!"Variables
var is mutable, let is immutable after assignment, const is compile-time constant.
var x = 10
let y = 20
const z = 30
echo x + y + zProcedures
Procedures use = for body assignment; last expression is returned.
proc add(a, b: int): int =
a + b
echo add(3, 4)Compilation
nim c compiles to C, nim js compiles to JavaScript.
# nim c -d:release main.nim
# nim js main.nim (compile to JS)Control Flow
If-Else
Indentation-based blocks, similar to Python.
let n = 5
if n > 3:
echo "big"
elif n == 3:
echo "three"
else:
echo "small"Case
case/of for multi-way branching.
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.
var i = 0
while i < 5:
echo i
inc iFor Loop
..< is exclusive range, .. is inclusive range.
for i in 0..<5:
echo i
for ch in "hello":
echo chData Structures
Sequences
@[] creates a seq (dynamic array).
var nums = @[1, 2, 3]
nums.add(4)
nums.insert(0, 0)
echo nums.lenStrings
Strings are mutable; slicing with .. works.
var s = "Hello"
s.add(" World")
echo s[0..4]
echo s.lenTables
Tables are hash maps.
import std/tables
var t = initTable[string, int]()
t["a"] = 1
t["b"] = 2
echo t["a"]Tuples
Tuples support unpacking.
let p = (10, 20)
echo p[0]
let (x, y) = p
echo x, yAdvanced
Templates
Templates are for metaprogramming — code expansion at compile time.
template twice(body: untyped) =
body
body
twice:
echo "repeated"Macros
Macros operate on AST for powerful code generation.
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.
try:
raise newException(ValueError, "bad")
except ValueError as e:
echo e.msgWas this helpful?