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