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.
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.
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.
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.
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.