The Standard Library Tour
21.1 Collections
import std/[tables, sets, deques, heapqueue, critbits, lists]
var ages = {"Ana": 30, "Bo": 25}.toTable # Table[string, int]
ages["Cy"] = 40
echo ages.getOrDefault("Zed", 0), ages.hasKey("Ana"), "Bo" in ages, ages.len
ages.del("Bo")
for k, v in ages: echo k, "=", v
ages.mgetOrPut("Dan", 0) += 1
var counts = initCountTable[string]()
for w in "a b a c a".split: counts.inc(w)
echo counts.largest
var ord = initOrderedTable[string, int]() # keeps insertion order
var refTab = newTable[string, int]() # TableRef (reference semantics)
var hs = toHashSet([1, 2, 3])
hs.incl 4
echo hs * toHashSet([2, 9]), 3 in hs
var dq = initDeque[int](); dq.addLast 1; dq.addFirst 0; echo dq.popFirst
var hq = initHeapQueue[int](); hq.push 5; hq.push 1; echo hq.pop # min-heap
var ll = initDoublyLinkedList[int](); ll.add 121.2 Key Modules Overview
std/strutils, strformat, unicode, strscans, parseutils Strings and parsing std/sequtils, algorithm, sugar Sequences and functional helpers
std/math, random, rationals, complex, stats, fenv, bitops
std/tables, sets, deques, heapqueue, lists, critbits std/times, monotimes Dates, durations, timing
std/os, osproc, paths, files, dirs, envvars, cmdline std/streams, memfiles Streams, memory-mapped files
std/json, jsonutils, marshal, parsecsv, parsexml, xmltree, parsecfg Serialization and parsing
std/net, asyncnet, httpclient, asynchttpserver, uri, smtp, nativesockets
std/asyncdispatch, asyncfile, selectors std/typedthreads, locks, atomics, isolation, channels (via threading pkg)
std/macros, typetraits, genasts, compilesettings std/logging, terminal, colors, parseopt, exitprocs CLI and logging
std/hashes, md5, sha1, base64, oids, sysrand Hashing and encoding std/re, nre Regular expressions (PCRE)
Moved to the db_connector package in Nim 2
21.3 Dates and Times
import std/[times, monotimes]
let now = now()
echo now.format("yyyy-MM-dd HH:mm:ss"), " ", now.weekday
let tomorrow = now + 1.days
let dt = parse("2025-10-24", "yyyy-MM-dd")
echo (tomorrow - now).inHours
let t0 = getMonoTime()
# ... work ...
echo getMonoTime() - t0 # Duration
echo epochTime(), getTime().toUnix21.4 Random Numbers and Math
import std/[random, math]
randomize() # seed
echo rand(1..6), rand(1.0), sample(@["a", "b", "c"])
var r = initRand(42); echo r.rand(100)
var s = @[1, 2, 3]; shuffle(s)
echo sqrt(2.0), pow(2.0, 10), 2^10, floor(3.7), round(3.456, 2), gcd(12, 18), lcm(4, 6)
echo PI, E, Inf, NaN.isNaN, clamp(15, 0, 10), floorDiv(-7, 2), euclMod(-7, 3)21.5 JSON
Faster third-party options: jsony, json_serialization (Status), sunny.
import std/json
let j = parseJson("""{"name": "Ana", "tags": ["a", "b"], "age": 30}""")
echo j["name"].getStr, j["age"].getInt, j["tags"][0], j{"missing"}.getStr("default")
let built = %* {"id": 1, "items": [1, 2, 3], "ok": true}
echo built.pretty
type User = object
name: string
age: int
let u = j.to(User) # deserialize into an object
echo %u # serialize