Nyx by Example
English
The best way to learn a language is to read real code. This collection of short, focused examples walks you through Nyx one concept at a time. Each recipe is self-contained: you can copy it, run it, and modify it to explore further.
No prior experience with Nyx is required. If you can read code in any C-like language, you will feel at home immediately.
Español
La mejor forma de aprender un lenguaje es leer código real. Esta colección de ejemplos cortos y enfocados recorre Nyx concepto por concepto. Cada receta es autocontenida: puedes copiarla, ejecutarla y modificarla para explorar más.
No se requiere experiencia previa con Nyx. Si puedes leer código en cualquier lenguaje similar a C, te sentirás en casa de inmediato.
Fundamentals
01
Hello World
The simplest Nyx program — printing text to the terminal.
02
Variables
Immutable
let, mutable var, basic types, and string interpolation.03
Functions
Defining functions with parameters, return types, and default arguments.
04
Control Flow
if/else, while loops, for-range, for-in, break and continue.
05
Arrays
Creating, indexing, pushing, and iterating over dynamic arrays.
06
Maps
Key-value storage with
Map.new(), insert, get, has, and key iteration.07
Strings
trim, length, substring, toUpper, split, contains, and interpolation.
08
Structs
Defining data types with fields and attaching methods via
impl.09
Enums
Algebraic data types with data-carrying variants and exhaustive
match.10
Closures
First-class functions that capture their enclosing environment.
I/O & Data
11
File Read & Write
Reading and writing files with
read_file and write_file.12
Stdin Input
Reading user input from the terminal with
read_line.13
CLI Arguments
Accessing command-line arguments with
get_args.14
Environment Variables
Reading env vars with
getenv and getenv_default.15
JSON Parse
Parsing JSON strings into Maps and Arrays.
16
JSON Serialize
Converting data structures back to JSON strings.
17
Regular Expressions
Match, extract, and replace with POSIX regex.
18
CSV Parsing
Splitting lines and fields to process tabular data.
19
Date & Time
Timestamps, formatted dates, and time measurement.
20
Threads & Channels
Spawning threads and communicating via channels.
Types & Patterns
21
Traits
Defining shared behavior with
trait and impl ... for.22
Trait Bounds
Constraining generics with
<T: Display>.23
Derive Macros
Auto-generating Clone, Debug, and other trait impls.
24
Option
Handling optional values with
Some and None.25
Result
Error handling with
Ok and Err.26
Try Operator
Short-circuit error propagation with
?.27
If Let
Destructuring enums in conditions with
if let.28
Match Guards
Adding conditions to match arms with
if guards.29
Iterator: Map & Filter
Lazy transformations with
.iter().filter().map().collect().30
Iterator: Fold
Reducing a sequence to a single value with
fold.Advanced
31
Iterator: Enumerate
Getting index and value pairs during iteration.
32
Iterator: Take & Skip
Slicing sequences with
take and skip.33
Recursion
Solving problems with functions that call themselves.
34
Sorting
Sorting arrays of integers and strings.
35
Error Handling
try/catch blocks for recovering from runtime errors.
36
Defer
Guaranteed cleanup with
defer { ... } blocks.37
Sleep & Timer
Pausing execution and measuring elapsed time.
38
Crypto: Hashing
SHA-256, MD5, and HMAC-SHA256 for integrity checking.
39
Random & UUID
Generating random numbers and unique identifiers.
40
Thread Spawn
Running functions concurrently with
thread_spawn.Networking & Protocols
41
Base64
RFC 4648 encoding/decoding — standard and URL-safe variants.
42
URL Encode
Percent-encoding, query strings, and HTML entity escaping.
43
TOML Config
Parsing configuration strings with
std/toml.44
MessagePack
Binary serialization — ~30% smaller than JSON.
45
DNS Resolve
Converting hostnames to IP addresses with
resolve.46
TCP Client
Connecting, writing, and reading over raw TCP sockets.
47
TCP Server
Listening, accepting, and echoing with
tcp_listen.48
UDP Socket
Connectionless datagrams with
udp_bind and udp_sendto.49
HTTP GET
High-level HTTP client requests with
std/http.50
HTTP POST
POST requests and custom methods with
http_request.51
HTTP Server
Minimal server with
http_serve and request routing.52
HTTP Middleware
Web framework with
App, routes, logging, and CORS.53
WebSocket
RFC 6455 framing, parsing, and handshake responses.
54
RESP Protocol
Building Redis wire-format messages manually.
55
SQLite
In-memory SQL database with
sqlite_open and sqlite_query.56
CSV Write
Creating and serializing CSV documents with
std/csv.Concurrency
57
Mutex
Protecting shared state between threads with locks.
58
Channel Patterns
Message passing with buffered channels and sentinels.
59
Worker Pool
Dispatching tasks to N threads via shared channels.
60
Producer-Consumer
Decoupled pipeline with bounded-channel backpressure.
61
WaitGroup
Waiting for multiple threads with
wg_add/wg_done/wg_wait.62
Semaphore
Limiting concurrent access with
sem_acquire/sem_release.63
Select Channel
Multiplexing channels with the
select statement.Systems
64
Fork & Exec
Running external commands with
fork, execvp, and waitpid.65
Pipes
Connecting processes with
pipe_new and dup2.66
Signal Handling
Registering signal callbacks with
signal_handle.67
File Watcher
Detecting file changes by polling with
stat.68
Process Control
PID, working directory, terminal detection, and file stat.
69
Raw Terminal
Character-by-character input with
raw_mode_enter.70
Shebang Script
Running Nyx files as executable scripts with
#!/usr/bin/env nyx.nyx-kv (Key-Value Store)
71
KV Basic
Connect to nyx-kv and issue SET/GET/DEL commands over RESP.
72
KV Lists
RPUSH, LPOP, LRANGE, LLEN for FIFO queues and stacks.
73
KV Hashes
HSET/HGET/HLEN for structured data like user profiles.
74
KV Auth
Multi-tenant authentication with tokens and namespaces.
75
KV Pub/Sub
Real-time messaging with SUBSCRIBE and PUBLISH.
76
KV Expire
TTL with EXPIRE, PERSIST, and SET EX for cache and sessions.
77
KV Pipelined
Batch commands for 250K+ ops/sec throughput.
nyx-serve (Web Framework)
78
Serve Routes
RESTful routing with GET/POST/PUT/DELETE and path params.
79
JSON API
Parse request bodies and build JSON responses with helpers.
80
Static Files
Serve CSS, JS, and images with
app_static and MIME detection.81
Sessions
Cookie-based sessions backed by nyx-kv with TTL.
82
Multi-threaded
http_serve_mt with N worker threads for 73K req/s.83
CORS
Cross-origin headers with
mw_cors and cors_configure.84
Full-stack
HTTP server + JSON API + nyx-kv backend in one binary.
nyx-proxy (Reverse Proxy)
85
Proxy Config
Parse
proxy.toml with std/toml.86
Virtual Hosts
Route by Host header to different upstreams.
87
Health Checks
TCP probe upstreams with threshold and auto-recovery.
88
Rate Limit
Per-IP sliding window returning HTTP 429 when exceeded.
89
TLS SNI
Multi-domain HTTPS on one port with Let's Encrypt certs.
Queue, DB & HTTP/2
90
Queue Enqueue
Persistent message queue with ENQUEUE and QLEN.
91
Queue Consumer
DEQUEUE + ACK/NACK loop with automatic redelivery.
92
DB SQL
CREATE/INSERT/SELECT over nyx-db RESP protocol.
93
DB Transactions
BEGIN/COMMIT/ROLLBACK for atomic operations.
94
HTTP/2 Server
Stream multiplexing and HPACK header compression.
95
HTTP/2 Frames
Binary frame types: DATA, HEADERS, SETTINGS, PING.
Full-stack Patterns
96
REST API
Complete CRUD API with middleware and nyx-kv backend.
97
Real-time Pub/Sub
WebSocket + nyx-kv Pub/Sub for live updates.
98
Microservice
Queue consumer with cache-aside pattern via nyx-kv.
99
Rate-limited API
Atomic INCR + EXPIRE for per-user rate limits.
100
Production Stack
Full nyxlang.com architecture: proxy + web + kv + queue.