By example
Nyx by example
Worked recipes, in order of difficulty. Each one is a program that compiles and runs with the version in the footer: read it, copy it, change it.
Fundamentals
- 01Hello WorldThe simplest Nyx program — printing text to the terminal.
- 02VariablesImmutable
let, mutablevar, basic types, and string interpolation. - 03FunctionsDefining functions with parameters, return types, and default arguments.
- 04Control Flowif/else, while loops, for-range, for-in, break and continue.
- 05ArraysCreating, indexing, pushing, and iterating over dynamic arrays.
- 06MapsKey-value storage with
Map.new(), insert, get, has, and key iteration. - 07Stringstrim, length, substring, toUpper, split, contains, and interpolation.
- 08StructsDefining data types with fields and attaching methods via
impl. - 09EnumsAlgebraic data types with data-carrying variants and exhaustive
match. - 10ClosuresFirst-class functions that capture their enclosing environment.
- 107continue in forSkip to the next element inside a for loop — over an array and over a range.
Input, output and data
- 11File Read & WriteReading and writing files with
read_fileandwrite_file. - 12Stdin InputReading user input from the terminal with
read_line. - 13CLI ArgumentsAccessing command-line arguments with
get_args. - 14Environment VariablesReading env vars with
getenvandgetenv_default. - 15JSON ParseParsing JSON strings into Maps and Arrays.
- 16JSON SerializeConverting data structures back to JSON strings.
- 17Regular ExpressionsMatch, extract, and replace with POSIX regex.
- 18CSV ParsingSplitting lines and fields to process tabular data.
- 19Date and TimeTimestamps, formatted dates, and time measurement.
- 20Spawn & ChannelSpawning threads and communicating via channels.
- 101File Errors: Two Tiers
Resultwhen the caller can react, panic when dying is the honest move. - 106JSON: exact numbersjson_stringify re-emits every number exactly as it came in; json_as_float goes through a double and loses the extra zeros.
- 116Barcodes and QR codesstd/barcode returns data, not drawings — QR, Code 128 and EAN-13 in pure Nyx, the same program native and in wasm.
- 118PDF invoicea letter-size invoice in pure Nyx — right-aligned amounts, a table made of text+line, a PNG logo and a QR, native and in wasm.
- 123Build and read a .zip filestd/zip in pure Nyx, no zlib: DEFLATE per entry, CRC-32 checked on read, limits against zip bombs.
- 124A purchase ledger as .xlsxstd/xlsx writes a real workbook in pure Nyx: typed cells, merged cells, frozen header, autofilter and thousands separators.
- 125Read an .xlsx sheetxlsx_read returns each cell with its type, ISO dates, gaps as empty cells, and default limits against zip bombs.
- 133Product photo thumbnailsstd/image decodes at the largest possible reduction, makes several sizes from one decode and flattens transparency onto white.
- 138An .xlsx bulk-upload template with dropdownsvalidate_list and validate_list_range restrict a column to allowed values; xlsx_fill marks rejected rows.
- 139A PDF that traces a pre-printed formstd/pdf phase 2: line width, gray and color fills, Times and Courier, rotated text, per-page graphic state.
- 140Thumbnails of scanned sheetsstd/image on letter-size scans: almost no reduction, so what matters is the build mode.
- 143Render a PDF page as an imagestd/pdf_render draws a page of a PDF into an
Imageon the server, with no external programs; what it cannot draw is either an error or a list you inspect. - 145A large CSV without split() per row
indexOffinds the commas andstring_to_float_rangeparses the number straight from the bytes, without creating a substring per field. - 146A large CSV by columns
try_csv_readparses a CSV in one pass straight into typed columns; acatcolumn arrives as integer codes plus a dictionary, so grouping is indexing an array.
Types and patterns
- 21TraitsDefining shared behavior with
traitandimpl ... for. - 22Trait BoundsConstraining generics with
<T: Display>. - 23Derive CloneAuto-generating Clone, Debug, and other trait impls.
- 24Option: Some and NoneHandling optional values with
SomeandNone. - 25Result: Ok and ErrError handling with
OkandErr. - 26Try OperatorShort-circuit error propagation with
?. - 27if letDestructuring enums in conditions with
if let. - 28Match GuardsAdding conditions to match arms with
ifguards. - 29Iterator: map and filterLazy transformations with
.iter().filter().map().collect(). - 30Iterator: foldReducing a sequence to a single value with
fold. - 105An Fn field in a structBind the field to a variable before calling it — the receiver can be a local variable, a by-value parameter or a nested field.
- 135Shadowing a name inside a blockA name redeclared in an if, loop, match arm or try is another variable that disappears at the closing brace.
- 136defer runs when its block closesdefer fires on leaving the block it is written in — fall-through, return, ?, break or continue — in LIFO order.
Advanced
- 31Iterator: enumerate()Getting index and value pairs during iteration.
- 32Iterator: take() and skip()Slicing sequences with
takeandskip. - 33RecursionSolving problems with functions that call themselves.
- 34SortingSorting arrays of integers and strings.
- 35Error Handlingtry/catch blocks for recovering from runtime errors.
- 36Defer and CleanupGuaranteed cleanup with
defer { ... }blocks. - 37Sleep and TimersPausing execution and measuring elapsed time.
- 38Cryptographic HashingSHA-256, MD5, and HMAC-SHA256 for integrity checking.
- 39Random Numbers and UUIDGenerating random numbers and unique identifiers.
- 40Thread SpawnRunning functions concurrently with
thread_spawn. - 102Template Engine, Flask-StyleInterpolation,
#if,#eachand partials withstd/template. - 109await in the browserAn async fn that waits on the JS host without splitting the flow into callbacks — wasm32-wasi with Asyncify.
- 114Offline IndexedDBA catalog and a sales queue that survive an F5 — await over IndexedDB, past localStorage's limit.
- 117Web Serial: thermal printer ticketESC/POS bytes straight to a POS printer from wasm32-wasi with await — no system print dialog, cut and cash drawer included.
- 121Keep a value across wasm eventsarena_persist copies a String or Array out of the per-event arena so a later event reads it intact — the fix for silently recycled memory.
- 128Verify a signed payment webhookstd/rsa checks an RSA-SHA256 signature against the provider's public key: PKCS#1 v1.5 or PSS, true, false or an error.
- 131Safe user formulas for payrollstd/expr parses once, evaluates per employee with fixed-point decimals, and reports the position of every error.
- 132A PWA talking to a local-network serverLocal Network Access permission plus a timeout on fetch and SSE, so a tablet does not wait minutes on a server that is off.
Networking
- 41Base64RFC 4648 encoding/decoding — standard and URL-safe variants.
- 42URL EncodePercent-encoding, query strings, and HTML entity escaping.
- 43TOML ConfigParsing configuration strings with
std/toml. - 44MessagePackBinary serialization: compact, typed, byte-oriented.
- 45DNS ResolveConverting hostnames to IP addresses with
resolve. - 46TCP ClientConnecting, writing, and reading over raw TCP sockets.
- 47TCP ServerListening, accepting, and echoing with
tcp_listen. - 48UDP SocketConnectionless datagrams with
udp_bindandudp_sendto. - 49HTTP GETHigh-level HTTP client requests with
std/http. - 50HTTP POSTPOST requests and custom methods with
http_request. - 51HTTP ServerMinimal server with
http_serveand request routing. - 52HTTP MiddlewareWeb framework with
App, routes, logging, and CORS. - 53WebSocketRFC 6455 framing, parsing, and handshake responses.
- 55SQLiteIn-memory SQL database with
sqlite_openandsqlite_query. - 56CSV WriteCreating and serializing CSV documents with
std/csv. - 103A model written once
#[derive(Fields)]andstd/postgres: the struct is the only source of truth for the schema. - 104No driver in between
std/postgresspeaks wire protocol v3 and SCRAM-SHA-256 in pure Nyx — connect, track migrations, and bind parameters without libpq. - 108HTTP: deadline and causeA client that gives up on time and tells WHY it failed: tls, timeout, connection.
- 110Server-Sent EventsA channel that doesn't hold a worker: the route runs the full pipeline, then broadcasts to a room.
- 113Sending mail with std/smtpMessage, attachment and dot-stuffing built in pure Nyx — STARTTLS on 587 or TLS from the greeting on 465.
- 115Repeated form/query keysform_values/query_values recover every value of a repeated key — checkboxes, <select multiple> — where req.form silently keeps only the last.
- 119LISTEN/NOTIFY as a live busPostgreSQL fans a notification out to every process's SSE rooms, only if it commits — no Redis in between.
- 120Idle keep-alive connectionsworkers is how many requests run at once, not how many connections stay open — an idle tab parks in the event loop and costs no thread.
- 122HTTPS to a site with a broken chainHttpOpts.cas_extra adds the missing intermediate certificate for ONE request, without turning verification off.
- 126Automatic gzip in std/serveText responses of 1 KiB or more leave compressed when the client sends Accept-Encoding: gzip — no code needed.
- 127Body caps and rate limits in std/serveA body cap per route (413) and a request limiter per origin (429 with Retry-After), shared by all workers.
- 129HTTPS with a client certificateMutual TLS per request: HttpOpts presents your certificate and key, validated BEFORE connecting.
- 130Upload a binary file as multipartmultipart_build and try_http_post_multipart send text fields plus a binary file, and a local server proves the bytes arrive intact.
- 134Turn incoming mail into casesstd/imap, std/mime and a UID checkpoint tie a customer's reply back to the quotation thread it answers.
- 137OAuth2 for a Gmail or Microsoft 365 mailboxstd/oauth2 builds the PKCE login URL, renews tokens and supports device code — the token imap_auth_xoauth2 and smtp_auth_xoauth2 expect.
- 141An email with a text AND an HTML versionsmtp_message_alternative builds multipart/alternative, combines with attachments and does not invent the text for you.
- 142Check SPF, DKIM and DMARC before sending mailstd/dns reads TXT and CNAME records and tells NXDOMAIN from NODATA; the checking logic is pure and testable without a network.
- 144Forward a streamed response as it arrives
try_http_streamreads another API's response piece by piece andsse_broadcastforwards each event to the browser the moment it lands.
Concurrency
- 57MutexProtecting shared state between threads with locks.
- 58Channel PatternsMessage passing with buffered channels and sentinels.
- 59Worker PoolDispatching tasks to N threads via shared channels.
- 60Producer-ConsumerDecoupled pipeline with bounded-channel backpressure.
- 61WaitGroupWaiting for multiple threads with
wg_add/wg_done/wg_wait. - 62SemaphoreLimiting concurrent access with
sem_acquire/sem_release.
Systems
- 64Fork & ExecRunning external commands with
fork,execvp, andwaitpid. - 65PipesConnecting processes with
pipe_newanddup2. - 66Signal HandlingRegistering signal callbacks with
signal_handle. - 67File WatcherDetecting file changes by polling with
stat. - 68Process ControlPID, working directory, terminal detection, and file stat.
- 69Raw TerminalCharacter-by-character input with
raw_mode_enter. - 70Shebang ScriptRunning Nyx files as executable scripts with
#!/usr/bin/env nyx. - 111nyx test --coverageWhich function in src/ no test called — homonyms from different modules never mix when measuring.
- 112include_bytesA binary resource that travels inside the executable, read at compile time — no dependence on the file reaching disk.