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

  1. 01Hello WorldThe simplest Nyx program — printing text to the terminal.
  2. 02VariablesImmutable let, mutable var, basic types, and string interpolation.
  3. 03FunctionsDefining functions with parameters, return types, and default arguments.
  4. 04Control Flowif/else, while loops, for-range, for-in, break and continue.
  5. 05ArraysCreating, indexing, pushing, and iterating over dynamic arrays.
  6. 06MapsKey-value storage with Map.new(), insert, get, has, and key iteration.
  7. 07Stringstrim, length, substring, toUpper, split, contains, and interpolation.
  8. 08StructsDefining data types with fields and attaching methods via impl.
  9. 09EnumsAlgebraic data types with data-carrying variants and exhaustive match.
  10. 10ClosuresFirst-class functions that capture their enclosing environment.

Input, output and data

  1. 11File Read & WriteReading and writing files with read_file and write_file.
  2. 12Stdin InputReading user input from the terminal with read_line.
  3. 13CLI ArgumentsAccessing command-line arguments with get_args.
  4. 14Environment VariablesReading env vars with getenv and getenv_default.
  5. 15JSON ParseParsing JSON strings into Maps and Arrays.
  6. 16JSON SerializeConverting data structures back to JSON strings.
  7. 17Regular ExpressionsMatch, extract, and replace with POSIX regex.
  8. 18CSV ParsingSplitting lines and fields to process tabular data.
  9. 19Date and TimeTimestamps, formatted dates, and time measurement.
  10. 20Spawn & ChannelSpawning threads and communicating via channels.
  11. 101File Errors: Two TiersResult when the caller can react, panic when dying is the honest move.

Types and patterns

  1. 21TraitsDefining shared behavior with trait and impl ... for.
  2. 22Trait BoundsConstraining generics with <T: Display>.
  3. 23Derive CloneAuto-generating Clone, Debug, and other trait impls.
  4. 24Option: Some and NoneHandling optional values with Some and None.
  5. 25Result: Ok and ErrError handling with Ok and Err.
  6. 26Try OperatorShort-circuit error propagation with ?.
  7. 27if letDestructuring enums in conditions with if let.
  8. 28Match GuardsAdding conditions to match arms with if guards.
  9. 29Iterator: map and filterLazy transformations with .iter().filter().map().collect().
  10. 30Iterator: foldReducing a sequence to a single value with fold.

Advanced

  1. 32Iterator: take() and skip()Slicing sequences with take and skip.
  2. 33RecursionSolving problems with functions that call themselves.
  3. 34SortingSorting arrays of integers and strings.
  4. 35Error Handlingtry/catch blocks for recovering from runtime errors.
  5. 36Defer and CleanupGuaranteed cleanup with defer { ... } blocks.
  6. 37Sleep and TimersPausing execution and measuring elapsed time.
  7. 38Cryptographic HashingSHA-256, MD5, and HMAC-SHA256 for integrity checking.
  8. 39Random Numbers and UUIDGenerating random numbers and unique identifiers.
  9. 40Thread SpawnRunning functions concurrently with thread_spawn.
  10. 102Template Engine, Flask-StyleInterpolation, #if, #each and partials with std/template.

Networking

  1. 41Base64RFC 4648 encoding/decoding — standard and URL-safe variants.
  2. 42URL EncodePercent-encoding, query strings, and HTML entity escaping.
  3. 43TOML ConfigParsing configuration strings with std/toml.
  4. 44MessagePackBinary serialization: compact, typed, byte-oriented.
  5. 45DNS ResolveConverting hostnames to IP addresses with resolve.
  6. 46TCP ClientConnecting, writing, and reading over raw TCP sockets.
  7. 47TCP ServerListening, accepting, and echoing with tcp_listen.
  8. 48UDP SocketConnectionless datagrams with udp_bind and udp_sendto.
  9. 49HTTP GETHigh-level HTTP client requests with std/http.
  10. 50HTTP POSTPOST requests and custom methods with http_request.
  11. 51HTTP ServerMinimal server with http_serve and request routing.
  12. 52HTTP MiddlewareWeb framework with App, routes, logging, and CORS.
  13. 53WebSocketRFC 6455 framing, parsing, and handshake responses.
  14. 55SQLiteIn-memory SQL database with sqlite_open and sqlite_query.
  15. 56CSV WriteCreating and serializing CSV documents with std/csv.

Concurrency

  1. 57MutexProtecting shared state between threads with locks.
  2. 58Channel PatternsMessage passing with buffered channels and sentinels.
  3. 59Worker PoolDispatching tasks to N threads via shared channels.
  4. 60Producer-ConsumerDecoupled pipeline with bounded-channel backpressure.
  5. 61WaitGroupWaiting for multiple threads with wg_add/wg_done/wg_wait.
  6. 62SemaphoreLimiting concurrent access with sem_acquire/sem_release.

Systems

  1. 64Fork & ExecRunning external commands with fork, execvp, and waitpid.
  2. 65PipesConnecting processes with pipe_new and dup2.
  3. 66Signal HandlingRegistering signal callbacks with signal_handle.
  4. 67File WatcherDetecting file changes by polling with stat.
  5. 68Process ControlPID, working directory, terminal detection, and file stat.
  6. 69Raw TerminalCharacter-by-character input with raw_mode_enter.
  7. 70Shebang ScriptRunning Nyx files as executable scripts with #!/usr/bin/env nyx.
Nyx, step by stepInstall it, write a first program, set up a project and hand it to an assistant.Open →