Erste Schritte
Hello World
echo ist ein eingebauter Befehl, der mit Zeilenumbruch nach stdout schreibt.
echo "Hello, World!"Variablen
var ist veränderbar, let unveränderlich nach der Zuweisung, const ist eine Compile-Zeit-Konstante.
var x = 10
let y = 20
const z = 30
echo x + y + zProzeduren
Prozeduren nutzen = für die Rumpfzuweisung; der letzte Ausdruck wird zurückgegeben.
proc add(a, b: int): int =
a + b
echo add(3, 4)Kompilierung
nim c kompiliert nach C, nim js nach JavaScript.
# nim c -d:release main.nim
# nim js main.nim (compile to JS)Kontrollfluss
If-Else
Einrückungsbasierte Blöcke, ähnlich wie Python.
let n = 5
if n > 3:
echo "big"
elif n == 3:
echo "three"
else:
echo "small"Case
case/of für mehrfache Verzweigung.
let day = "Mon"
case day
of "Mon": echo "Monday"
of "Tue": echo "Tuesday"
else: echo "Other"While-Schleife
inc ist ein eingebauter Befehl, der in place hochzählt.
var i = 0
while i < 5:
echo i
inc iFor-Schleife
..< ist ein exklusiver Bereich, .. ein inklusiver.
for i in 0..<5:
echo i
for ch in "hello":
echo chDatenstrukturen
Sequences
@[] erzeugt eine seq (dynamisches Array).
var nums = @[1, 2, 3]
nums.add(4)
nums.insert(0, 0)
echo nums.lenStrings
Strings sind veränderbar; Slicing mit .. funktioniert.
var s = "Hello"
s.add(" World")
echo s[0..4]
echo s.lenTables
Tables sind Hash-Maps.
import std/tables
var t = initTable[string, int]()
t["a"] = 1
t["b"] = 2
echo t["a"]Tuples
Tuples unterstützen Unpacking.
let p = (10, 20)
echo p[0]
let (x, y) = p
echo x, yFortgeschritten
Templates
Templates dienen der Metaprogrammierung — Code-Expansion zur Compile-Zeit.
template twice(body: untyped) =
body
body
twice:
echo "repeated"Macros
Macros operieren auf dem AST für mächtige Codegenerierung.
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 folgen dem raise/except-Muster.
try:
raise newException(ValueError, "bad")
except ValueError as e:
echo e.msgWas this helpful?