Low

Standard library

import std/file
import std/http
import std/http/websocket
import std/io
import std/net

fn handle(req: http.Request) -> http.Response {
    if req.path == "/chat" {
        using ws = websocket.accept(req) catch {
            _ => return http.response(400, "")
        }
        let m = websocket.receive(ws) catch {
            _ => return http.upgraded()
        }
        websocket.send_text(ws, str(m.data)) catch {
            _ => {}
        }
        return http.upgraded()
    }
    http.response(200, file.read_text("index.html") catch "missing")
}

fn main() ! io.Error {
    let client = http.client().with_bearer_token("token").with_timeout(5000).build()
    let page = client.get("https://example.com/") catch {
        _ => return
    }
    using l = net.listen("", 8080)?
    http.serve(l, handle)?
}

import std/<name> loads a standard library module. The library is compiled into low, and the project root is not searched for it.

Every module except std/math and std/sql/sqlite talks to the kernel through raw syscalls. std/math calls libm and std/sql/sqlite calls libsqlite3 through extern blocks. A library is linked only when reachable code calls it, so a program stays static unless it calls one of their C functions.

ModuleContents
std/ioError, the error type shared by the I/O, codec and protocol modules. Stream, a copyable struct of read, write and close closures that views a resource. Guard and Lease (guard, enter, retire), the shared state that makes a closed descriptor fail with NotConnected instead of reaching a reused descriptor. A buffered Reader over a stream or, with bytes_reader, over a buffer, with read_line, read_exact, read_some, read_byte, buffered and fill. write_all, read_all, buffer(n), copy, and big- and little-endian byte helpers.
std/fileOpening: open, create, append and update return a droppable File whose handle is a copyable FileHandle. On a File: read, write, write_all, seek, sync, truncate, close, info and stat. On a FileHandle: read_on, write_on, write_all_on, close_on and stream_on. Whole files and directories: exists, read_file, read_text, write_file, write_text, remove, remove_dir, rename, mkdir, mkdir_all, list and stream. read_file sizes its buffer from the file's size; a file that reports no size, such as one under /proc, is read into a 64 KB buffer that doubles when full. Permission bits: create_mode, write_file_mode, write_text_mode, mkdir_mode and mkdir_all_mode take them, the other creators use 0o644 for files and 0o755 for directories, all are filtered by the process umask, and chmod is not. Locks: try_lock and unlock are advisory flock locks that report a held lock as false instead of waiting. remove_all removes a tree without following symbolic links. temp_dir creates a private directory under /tmp. Info also carries regular, link, accessed, uid, gid, device and inode. Further functions: lstat, is_dir, is_file, is_symlink, symlink, link, readlink, realpath, chown, lchown, set_times, disk_usage and read_dir_info. walk is a sorted depth-first walk that uses lstat, never descends into symbolic links and lets its callback return Continue, Skip or Stop. glob matches each segment with path.matches and supports **. copy and copy_dir keep file modes and recreate symbolic links. temp_file(dir, pattern) creates a uniquely named file with O_EXCL and mode 0600 and returns a droppable TempFile that closes and removes it unless keep is called. temp_dir_pattern makes a 0700 directory the same way.
std/file/watchinotify. watch and watch_with take paths and Options (recursive, access) and return a droppable Watcher with a copyable WatcherHandle. On a watcher: add, remove, next, events and stop. next parks the green thread until an Event (watched, name, path, kind, dir, cookie) arrives. events is a chan[Event] fed by a forwarding green thread. Kind is Created, Modified, Deleted, MovedFrom, MovedTo, Attrib, Closed, ClosedUnmodified, Opened, Accessed, SelfDeleted, SelfMoved or Overflow.
std/netAddresses: IPv4 and IPv6 Addr, parse_ip, format_ip, parse_addr, format, in_network (tests an address against a CIDR prefix) and is_global (false for addresses the IANA special-purpose registries mark as not globally reachable, and for multicast). Types: the droppable Listener, Conn and Socket, each with a copyable ListenerHandle, ConnHandle or SocketHandle in its handle field; adopt and detach convert between a ConnHandle and a Conn. TCP: listen, accept, accept_handle (returns the connection's view for a green thread to adopt), connect, dial and their _within forms with a connect timeout, connect_through (binds the socket to a network interface first), connect_first (tries a list of addresses in order through an optional interface) and interface_index. Connection I/O: read, write, write_all, close, shutdown_write, set_nodelay, read and write timeouts and stream, with read_on, write_on, write_all_on, close_on and stream_on on the view. UDP: bind_udp, send_to, receive_from and close_socket. lookup tries an IP literal, then /etc/hosts, then A and AAAA queries to each /etc/resolv.conf nameserver. An Addr with an empty ip is a Unix address: listen_unix, connect_unix, connect_unix_within and socketpair return the same Listener and Conn, abstract names start with @ or NUL, and a listener unlinks its pathname when closed. peer_credentials returns the peer's credentials. listen_with and bind_udp_with take ListenOptions (reuse_addr, reuse_port, backlog). Socket options: set_keepalive and set_buffer_sizes. UDP multicast: join_group, leave_group, set_multicast_ttl, set_multicast_loop and set_multicast_interface. Dialer is a function value that makes a connection; direct_dialer is the plain one.
std/socksSOCKS5 (RFC 1928, with RFC 1929 username and password) and SOCKS4a clients: dial, dial4a, tunnel and tunnel4a over an existing connection, and dialer and dialer4a, which return a net.Dialer. The proxy resolves the target name.
std/pipePipelines. A Pipe owns a Reader and a Writer, each droppable so that releasing it completes it, with copyable ReaderHandle and WriterHandle views for green threads (adopt_reader, adopt_writer and the _on operations). Also segmented buffers, backpressure, Sequence and SequenceReader, and adapters between pipes and streams.
std/cancelToken with token, child, cancel, cancelled, check and done (a channel that closes on cancellation, for select). on_cancel returns a droppable Registration that releases its callback; release, on_cancel_handle and release_on work on the copyable RegistrationHandle. pause is a sleep that ends early on cancellation.
std/httpServer types: Request, Response, Header, header helpers and parse_url. Request.token is cancelled when the client goes away and when the handler returns. Request.remote is the client's IP address for connections served by serve, serve_tls and serve_conn. Serving: serve, serve_tls, serve_conn and serve_stream; the _on forms (serve_on, serve_tls_on, serve_conn_on) take the listener's or connection's view. Client: a pooled client configured through client() and with_* builders, per-request builders, send, stream_to and download. with_interface binds every connection to a network interface. with_resolver substitutes for net.lookup on host names; TLS keeps the host name for SNI and certificate checks. with_cancel makes a request fail with Cancelled once its token is cancelled. URLs: parsing, resolution and encoding. connect returns a droppable Connection that closes its stream when released; detach hands the stream on. Proxies: with_proxy, with_http_proxy, with_https_proxy, with_no_proxy, with_proxy_from_environment and with_dialer send requests through an http:// proxy (absolute-form for http targets, CONNECT for https targets) or a socks5://, socks5h://, socks4:// or socks4a:// proxy. no_proxy follows Go's matching rules. CookieJar is a shared RFC 6265 jar (cookie_jar, with_cookie_jar, jar_set, jar_header, jar_cookies, jar_clear) that enforces the Secure rules and the __Secure- and __Host- prefixes and has no public-suffix check. A Response whose stream is a chan[[]u8] is written as it is produced, chunked on HTTP/1.1 and as DATA frames on HTTP/2, until the handler closes the channel.
std/http/websocketaccept and dial over ws and wss return a droppable Socket that sends a normal close when released. Operations: receive, send_text, send_binary, ping and close, with _on forms, and adopt and detach on the *SocketHandle.
std/http/sseServer-sent events. Shared: Event (id, event, data, retry), format, comment and keepalive. Server: stream, stream_with, serve_events, serve_events_with, Emitter and last_event_id. Client: parser, feed, parse and listen, which reads a text/event-stream response with any chunking and CR, LF or CRLF line ends.
std/http/filesserve_file and serve_file_with answer a request from a file. Content type comes from the extension, then sniffing. Weak ETag and Last-Modified work with If-None-Match and If-Modified-Since. A single Range is answered as 206 or 416, with If-Range. HEAD is supported and the body is streamed.
std/webA router with groups, middleware and typed JSON endpoints, problem details (RFC 9457), an OpenAPI 3.1 document built from the types, cookie sessions, CSRF protection, API key, Basic and bearer authentication, CORS and response compression. static and static_with serve a directory. events and event_stream serve server-sent events.
std/tlsTLS 1.2 and 1.3 clients and servers. client, server and dial return a droppable Session that sends close_notify and closes the stream beneath it when released. Its handle is the shared *SessionHandle holding protocol, version, group, suite, cipher_suite and peer_certificates. client_handle and server_handle return the view alone, and read_on, write_on, close_on and stream_on operate on it.
std/serdeThe Writer and Reader protocols, write[T], read[T] and schema[T] (which the compiler derives for every type), and Field[T, F].
std/jsonA reader and writer over UTF-8 bytes, the Value document model, equal (compares numbers numerically and objects without regard to member order), and serialize[T] and deserialize[T] with naming policies.
std/json/pointerRFC 6901 pointers: escape, unescape, parse, format, get, has, set, add, replace, remove and relative pointers. Edits return a new document.
std/json/patchRFC 6902 apply (atomic, failing with the operation's index) and diff; RFC 7396 merge_patch and merge_diff.
std/json/pathRFC 9535 JSONPath: compile, query, find, values and paths, with slices, filters, match, search, length, count and value, normalised paths, and syntax errors at a byte offset.
std/json/schemaJSON Schema 2020-12. compile and compile_with check the schema, resolve $ref, $anchor, $dynamicRef and registered resources, and precompile patterns. validate returns Violations with the instance pointer, the keyword pointer and a message. unevaluatedProperties and unevaluatedItems use annotations from the branches that passed. format annotates or asserts.
std/cborCBOR (RFC 8949): the Value model, a decoder with depth and length limits, a deterministic encoder, diagnostic notation, and serialize[T] and deserialize[T].
std/webauthnA WebAuthn relying party: registration and authentication options as JSON, registration and authentication verification for ES256, EdDSA and RS256 credentials, and COSE key parsing.
std/sqlThe driver contract: Connection, the droppable owner that closes the driver connection when released; ConnectionHandle, the copyable view of closures that std/orm and closures use (handle makes it from an owner, adopt the other way); Value, Rows, Error, Options and dialect helpers.
std/sql/postgresA PostgreSQL driver over protocol 3.0, plain or over TLS.
std/sql/sqlserverA Microsoft SQL Server driver over TDS 7.4, plain or over TLS.
std/sql/sqliteSQLite through libsqlite3, linked only when a program calls it. open and open_with (read-only, create, busy timeout). exec runs scripts. query, each and execute take ? or ?N parameters over cached prepared statements. Also last_insert_id, begin, begin_immediate, commit and rollback, and backup to a file through the online backup API. close and close_on are idempotent; a closed Database fails with sql.Error.Closed. connection and connect present a database as an sql.Connection: the one connection returns leaves closing to the Database, the one connect returns closes it. Calls block their OS thread.
std/sql/poolA pool of connections made by an opener. open takes a Config (max, max_idle, idle_timeout, max_lifetime, wait_timeout, ping_after, ping, clock). acquire and acquire_until (with a cancel token) park in first-in first-out order while every connection is in use. A droppable Lease returns its connection on release. Also with, discard, prune, stats and shutdown.
std/sql/migrateOrdered migrations recorded in a schema_migrations table with a SHA-256 checksum: plan, with_table, status, up, up_to and down, each migration in its own transaction under a lock. from_text and load_dir read -- +up and -- +down files named NNN_name.sql.
std/tomlTOML 1.0.0: a table tree, an encoder, and serde binding.
std/yamlYAML 1.2.2: events, a node tree, an encoder, and serde binding.
std/otelOpenTelemetry traces, metrics and logs with W3C propagation, OTLP/HTTP protobuf and JSON, OTLP/gRPC and console exporters, and the instrumentation used by std/http, std/web, std/sql/postgres, std/sql/sqlserver and std/orm.
std/protobufThe protobuf wire format: an encoder with nested messages and packed fields, and a field decoder.
std/xmlXML 1.0 with namespaces: a pull reader, a tree, a writer, and serde binding.
std/ormTyped queries over field references, row mapping, inserts, updates and deletes, tables created from types, and raw queries mapped onto structs, over an sql.ConnectionHandle.
std/compress/deflateDEFLATE, zlib and gzip.
std/compress/xzxz with LZMA2, and .lzma.
std/compress/zstdZstandard (RFC 8878).
std/compress/lz4LZ4 frames.
std/compress/brotliBrotli (RFC 7932).
std/compress/bzip2compress(data, level), decompress(data, limit), a streaming decode and an Encoder. The decoder reads multiple streams and blocks and checks both CRCs. Randomised blocks fail with Unsupported.
std/compress/snappyRaw blocks (compress_block, decompress_block, decoded_length) and the framing format with masked CRC-32C (compress, decompress, decode, Encoder).
std/hashOne-shot and incremental forms of CRC-32, CRC-32C, Adler-32, CRC-64 and xxHash32/64. Also FNV-1 and FNV-1a in 32 and 64 bits; SipHash-2-4 and SipHash-1-3 with a 16-byte key in 64- and 128-bit forms; MurmurHash3 (murmur3_32, murmur3_128); wyhash final 4.2; jump consistent hashing; and rendezvous hashing.
std/bitsDense bitsets.
std/bits/roaringRoaring bitmaps with the portable serialization format.
std/imageBitmaps, pixel operations and resizing, with PNG, JPEG, GIF, BMP, QOI and lossless WebP codecs.
std/cryptosha1, and random, which reads getrandom.
std/crypto/hashAlgorithm and cloneable Digest, SHA-256, SHA-384 and SHA-512, HMAC, HKDF and constant-time equal.
std/crypto/sha3SHA3-256, SHA3-384, SHA3-512, SHAKE128 and SHAKE256.
std/crypto/aeadAead values for AES-128-GCM, AES-256-GCM, ChaCha20-Poly1305 and XChaCha20-Poly1305 (xchacha20_poly1305, 24-byte nonce). The AES block functions for 128-, 192- and 256-bit keys (aes_key, encrypt_block_into, decrypt_block, decrypt_block_into). The ChaCha20 functions chacha20_xor (takes the RFC 8439 block counter) and hchacha20.
std/crypto/md5MD5 as a hash.Algorithm, so HMAC, HKDF and PBKDF2 work over it, and sum. For interop and checksums, not security.
std/crypto/cipherAES in CBC, raw (cbc_encrypt, cbc_decrypt) or with PKCS#7 padding (cbc_seal, cbc_open, pkcs7_pad, pkcs7_unpad); in CTR with a 128-bit big-endian counter (ctr); and in XTS with ciphertext stealing (xts, xts_encrypt, xts_decrypt). There is no ECB, and CBC provides no integrity: use an Aead.
std/crypto/x25519, std/crypto/ed25519X25519 key agreement (RFC 7748) and Ed25519 signatures (RFC 8032), over std/crypto/curve25519.
std/crypto/ecdsaECDH and ECDSA on P-256 and P-384, with RFC 6979 nonces and SEC1 private keys.
std/crypto/rsaRSA PKCS#1 v1.5 and PSS signing and verification, and PKCS#1 keys.
std/crypto/blake3BLAKE3: sum, xof, keyed_hash, derive_key, an incremental Hasher with finalize and seekable finalize_at, and algorithm(), a hash.Algorithm for HMAC.
std/crypto/otpHOTP (RFC 4226) and TOTP (RFC 6238) over SHA-1, SHA-256 and SHA-512: hotp, totp, verify_totp with a window, verify_hotp, generate_secret, base32 secrets, and otpauth:// uri and parse_uri.
std/crypto/mlkemML-KEM-512, -768 and -1024 (FIPS 203).
std/crypto/joseJSON Web Tokens: compact JWS with HS256/384/512, RS256/384/512, PS256/384/512, ES256, ES384 and EdDSA, JWK sets, and claim checks.
std/crypto/passwordPassword hashes in PHC strings: Argon2id, scrypt (RFC 7914, with a memory limit checked before allocating) and PBKDF2. bcrypt ($2b$; passwords over 72 bytes are rejected). verify handles all of them and $2a$ and $2y$ bcrypt strings. BLAKE2b.
std/crypto/x509DER, PEM, certificates, PKCS#8 private keys, the system roots, chain validation and TLS signature schemes.
std/timenow (Unix seconds), now_millis and now_nanos (the wall clock at finer resolution), monotonic (nanoseconds), sleep_for (rounds up to whole milliseconds), after, Timer and Ticker (their channels work in select), and Stopwatch. Calendar and zone types live in the submodules below, one module per type, so d.plus(span.days(3)) resolves to date.plus.
std/time/faultFault (OutOfRange, Invalid, Syntax(at), Overflow, UnknownZone, Malformed, Unsupported, Skipped, Ambiguous, OffsetConflict), the error every fallible time function returns, and to_string.
std/time/durationDuration, an exact signed elapsed time with private seconds and nanoseconds. Constructors from nanoseconds to hours, and from_seconds_f64. Arithmetic: plus, minus, times, divide, ratio, negate, abs, with try_ forms returning an optional. Plain forms panic on overflow. Also round and truncate with a Rounding, comparison, to_string (ISO 8601 PT1H30M), friendly (1h 30m) and parse, which reads both forms and fails at the offset of the first bad character.
std/time/timestampTimestamp, a point on the UTC timeline from 0001-01-01 to 9999-12-31 with nanosecond precision: now, from_unix in seconds, milliseconds or nanoseconds, plus and minus by Duration, until and since, round, truncate, RFC 3339 to_string and parse (offset required, :60 read as :59), and to_http_date and parse_http_date (IMF-fixdate, RFC 850 and asctime).
std/time/clockClock, a pair of closures for the wall and monotonic readings, with system, fixed and manual. A Manual clock moves with advance and set, so code that asks for the time is tested without sleeping.
std/time/spanSpan, a calendar amount of years, months, weeks, days and time units with one sign. Unit, Diff (largest, smallest, increment, mode), to_duration and from_duration, ISO 8601 to_string (P1Y2M3DT4H), friendly and parse.
std/time/roundingRounding (Trunc, Ceil, Floor, Expand and the five Half modes) and the helpers the other time modules share.
std/time/dateDate with private fields and validated constructors (of, clamped, from_epoch_days, from_ordinal, from_iso_week, from_weekday_in_month). Month, Weekday and IsoWeek. plus and minus by Span with month-end clamping, until and since with a Diff, next_weekday and on_or_next, and range. ISO 8601 to_string and parse (calendar, ordinal and week dates). format and parse_with over a pattern.
std/time/timeofdayTimeOfDay to the nanosecond. plus fails past midnight and plus_wrapping wraps. Also until, round, truncate, to_string, parse, and pattern format and parse_with.
std/time/datetimeDateTime, a civil date and time of day with no zone: plus by Span or Duration, until and since with a Diff, round, truncate, to_string, parse (an offset is rejected), and pattern format and parse_with.
std/time/offsetOffset, a UTC offset in whole seconds within ±25:59:59, with utc, hours, hm, to_string, to_string_z and parse.
std/time/zoneIANA zones. Zone is a shared value decoded once, from named (the host database, honouring ZONEINFO), load_from (any fn(str) -> []u8?), local (TZ, /etc/localtime, /etc/timezone, then UTC), from_posix, decode, utc or fixed. Queries: info_at, candidates (One, Overlap, Gap for a civil time), next_transition, previous_transition and transitions.
std/time/tzdataAn embedded copy of the database for hosts without one: source (for zone.load_from), names and version. The data is linked only when source or names is reachable.
std/time/zonedZoned, a Timestamp seen through a Zone whose offset is always the zone's own. Built from a civil time with a Disambiguation (Compatible, Earlier, Later, Reject) or strict. plus by Span moves calendar units on civil dates and time units by elapsed time; plus_duration is exact. Also until and since with a Diff, start_of_day, hours_in_day, series and round. RFC 9557 to_string (2026-11-11T10:00:00+00:00[Europe/London]), to_rfc3339, to_rfc2822, and parse with an OffsetPolicy for a written offset that disagrees with the zone. Pattern format and parse_with.
std/time/patternCompiled strftime and strptime patterns shared by the types above: compile, Names for other languages, render and scan. Verbs: %Y %y %C %m %d %e %j %b %B %a %A %u %w %U %W %V %G %H %I %M %S %f %N %p %P %z %:z %::z %Z %s %F %T %R %D %% %n %t. Flags: -, _, 0 and ^. Parsing is strict, and every error carries a byte offset.
std/time/humanizeago, relative, in_words, compact and round_to over a Words value; English by default.
std/simdVector reads and writes, splat, mask, blend, min, max, lane access, byte shuffles, bit counting and find_byte.
std/textParsing and formatting: integer parsing in any base from 2 to 36; correctly rounded float parsing, which allocates only to expand a decimal when digits beyond the 19th decide the rounding; parse_bool, radix, hex and hex encoding; fixed(x, places), which rounds half to even on the exact binary value. Trimming and splitting: trim and its start, end, prefix and suffix forms; split on a byte; split_str on a string (an empty separator splits into code points); fields; lines (drops a final empty line and \r before \n); chars; join. Searching: index, last_index, contains, count, starts_with, ends_with. Rewriting: repeat, replace, ASCII upper and lower (return their argument when no byte changes), and case-insensitive equal_fold and starts_with_fold (allocate nothing). Widths: char_count, from_char, and pad_left and pad_right to a width in code points. append and append_char onto a []u8. Comma-separated token lists. cut and last_cut return a Cut of before, after and found. strip_prefix and strip_suffix return str?. Also split_n, title, quote and unquote (backslash, \x, \u and \U escapes, failing with QuoteError), edit_distance over code points, wrap to a width, is_ascii and reverse.
std/text/diffMyers line diff: diff, lines, stats, distance, similarity, GNU-compatible unified and hunks, patch and patch_within over a unified diff, and word and character level inline, inline_chars and inline_markup.
std/text/tableTable with per-column Align, width limits, truncation and wrapping, and Border styles None, Ascii, Unicode, Markdown and Tabs. Widths use unicode.text_width and ignore ANSI sequences. align and align_tabbed align tab-separated cells like Go's tabwriter.
std/text/namingwords, snake, kebab, dotted, screaming_snake, camel, pascal, title, sentence, the matching is_ predicates, and slug and slug_with (transliterate Latin letters and cut at a word boundary).
std/text/numberformat_bytes and parse_bytes in decimal and binary units, grouped, ordinal, percent, compact, si, English words, and roman with parse_roman. Arithmetic is exact.
std/builderA Builder over a growing byte buffer, appended in place through mut: write, write_bytes, write_byte, write_char, write_i64, write_f64, write_line, write_repeat, write_join, len, capacity, reserve, truncate, reset, to_str and to_bytes.
std/regexLinear-time regular expressions in the RE2 style: compile and compile_with with Flags, generated (a pattern compiled into specialised code at build time), is_match, find, full_match, find_all, replace_all (with a closure receiving each Match), split and split_n. A match offers start, end, text, group and span, with byte offsets.
std/unicodeNormalization (Unicode 16.0.0): nfd, nfkd, nfc and nfkc; combining_class; full case folding with casefold; search_key, which case-folds, applies NFKD and drops combining marks in one pass. Properties: category, is_letter, is_upper, is_lower, is_digit, is_space, is_punct, is_identifier_start and the other predicates; east_asian_width, display_width and text_width; script. Case mapping: to_upper, to_lower and to_title, and upper and lower with SpecialCasing but without final-sigma or locale rules. Segmentation: UAX #29 graphemes, grapheme_count and grapheme_end. UTF-8 helpers: decode_rune, encode_rune, utf8_valid, utf8_to_valid. Category, width and identifier data are Unicode 16.0.0; script, grapheme break and case data come from 17.0.0 restricted to characters assigned in 16.0.0. The tables are generated by cmd/tablegen and linked only when a function that reads them is reachable.
std/unicode/utf16, std/unicode/utf32Encoding and decoding of code points, []u16 and []u32, and byte forms in either order with BOM handling, strict or lossy, with surrogate validation.
std/charsetdecode, decode_lossy, encode, encode_replace, canonical (WHATWG labels) and detect_bom for UTF-8, UTF-16, UTF-32, ISO-8859-1, -2 and -15, windows-1250, -1251 and -1252, KOI8-R, IBM437 and IBM850. The CJK encodings are not provided.
std/htmlAn HTML tokenizer: a pull Tokenizer returning StartTag, EndTag, Text, Comment, Doctype and End tokens, attribute lookup and unescape for character references.
std/mathlibm's trigonometric, hyperbolic, exponential and rounding functions, pi, tau, e, infinity, nan, is_nan, is_inf, generic abs, min, max and clamp, and integer ipow and gcd.
std/slicesQueries and transforms: contains, index, clone, concat, reverse, map, filter, fold, any, all, sum, min and max (as optionals), sorted. Sorting: sort and sort_by are unstable and in place, a quicksort with median-of-three pivots that recurses into the smaller side and finishes runs of 16 or fewer with insertion sort. sort_stable and sort_stable_by are a top-down merge sort; sort_by_key is stable. Also reduce, count, find, find_index, first, last, equal, compare, starts_with, ends_with, unique (adjacent duplicates), flat_map, flatten, repeat, lower_bound, binary_search (the first match) and binary_search_by. take, skip, chunks and windows share the source's elements. partition and zip work over Pair[A, B]. fill, swap, rotate, insert and remove are in place. Slices are not named types, so these are called with a pipe: xs |> slices.sort().
std/mapskeys, values, sorted_keys, entries, from_pairs, clone, merge (the right map wins), filter, map_values, has, get_or, invert, count_by and group_by.
std/osProcess state: args and environment (from the argument and environment vectors the program started with), env as str?, umask (sets the creation mask and returns the previous one), pid and exit. Queries: getcwd, chdir, hostname, uid, gid, euid, egid, ppid, executable, uptime, cpu_count, and lookup_user and user_name from /etc/passwd. set_env and unset_env are seen by env, environment, process.find and the environment process.run passes on. Directories: home_dir, cache_dir, config_dir, data_dir and state_dir (XDG variables when absolute, otherwise under $HOME), and temp_dir_path.
std/os/signalSignal (Hangup, Interrupt, Quit, Abort, Kill, User1, User2, Pipe, Alarm, Terminate, Child, Continue, Stop, TerminalStop, WindowChange) with number, name, from_number and catchable. notify returns a droppable Watch (copyable WatchHandle) whose signals channel delivers the caught signals, with wait_for, wait_timeout, wait_any and stop. Also ignore, reset, send and raise. Kill and Stop cannot be caught and fail with Invalid.
std/processCommand with arguments, an optional replacement environment, a working directory, Inherit, Piped or Null for each standard stream, and an optional new process group. start returns a droppable Child that kills and reaps an unwaited process and closes its pipes when released. start_handle, adopt, wait, kill, and wait_on and kill_on on the shared ChildHandle. run feeds input and collects both outputs. find searches PATH. success.
std/cdpThe Chrome DevTools Protocol. launch starts a headless Chromium with a disposable profile, connects to it and returns a droppable Browser that shuts it down when released. Its handle is the shared *BrowserHandle; launch_handle, adopt, shutdown_on and open_page_on take it. call sends a command to the browser or a session, and events delivers everything else. open_page opens a page in its own browser context whose every request, including those of cross-site frames and workers, passes through Handlers. Also navigate and shutdown.
std/pathSlash-separated path manipulation: clean (lexical, resolving . and ..), join, base, dir, ext, stem and is_absolute. matches matches shell globs with *, ?, [...] classes (ranges, ! or ^ negation) and \ escapes; no wildcard crosses a /.
std/syncMutex with lock, try_lock, unlock and locked. WaitGroup with add, done and wait. Once with run. RwLock, first in first out and writer-fair, with read_lock, read_unlock, write_lock, write_unlock, try_read_lock, try_write_lock, reading and writing. Semaphore with acquire, try_acquire, release and available. Cond with wait_cond, signal and broadcast. Barrier with wait_barrier. OnceValue[T]. ErrorGroup[E], whose go blocks while limit tasks run and whose join returns the first error. All are built on channels, so a waiting green thread parks instead of spinning.
std/retryPolicy with attempts, base, multiplier, maximum delay, Jitter (None, Full, Equal, Decorrelated), a deadline, a seeded Rng and a cancel token. delay; a loop driver start with next and at_least; run over a Step (Done, Retry, RetryAfter, Fatal) giving an Outcome.
std/ratelimitBucket (token bucket in exact nanosecond units) with allow, allow_n, reserve, wait and set_rate. Window, a sliding log. Keyed, a bounded per-key set of buckets with idle eviction. All take a clock.Clock.
std/singleflightGroup[K, V] with do, do_shared, forget and in_flight, which run one call per key while the others wait for its result. Expiring[V], a value refreshed at most once per interval.
std/atomicInt, Bool and Flag built on compare-and-swap, with load_int, store_int, add_int, swap_int, compare_and_swap_int and update_int, and the same forms for Bool. Every load is a locked operation, so a loop cannot hoist it. Value[T] swaps a heap pointer under a lock: load_value, store_value, swap_value, update_value, snapshot_value and compare_and_swap_value (compares pointer identity).
std/randA seedable, non-cryptographic xoshiro256** generator: seeded, rng (all 256 bits of state from std/crypto), next, unbiased below and between, float, chance, shuffle and pick. pcg32, pcg64 and chacha (seeded from 32 bytes; chacha_rng seeds from entropy) produce an Rng that every function accepts, and next32 draws 32 bits. Distributions: normal, exponential, gamma, beta, poisson, binomial, geometric, zipf, weighted_pick, cumulative with pick_cumulative, sample and permutation. Use std/crypto for secrets.
std/uuidRandom v4 and time-ordered v7 UUIDs, format, parse (reports the offset of the first bad character), version, timestamp for v7, equal and nil.
std/csvRFC 4180 records with quoted fields, doubled quotes, embedded newlines and CRLF or LF line ends. parse and parse_with a separator fail with the line of an unterminated or bare quote. format, format_with and append_record quote only fields that need it.
std/dotenv.env files. parse and read return a map from NAME=value lines. They allow export, blank lines, # comments (inline after whitespace in unquoted values), single quotes taken literally, and double quotes with \n, \t and \r escapes that may span lines. Errors carry the line.
std/flagCommand-line flags from Specs with help text, booleans and defaults: --name value, --name=value, single-dash forms and --. get, enabled, number, the remaining arguments, and usage.
std/logLeveled line logging (debug, info, warn, error) to a descriptor (stderr by default) as level prefix: message, without timestamps so journald and other collectors add their own. with_prefix nests a prefix. A Logger also carries attributes (str_attr, int_attr, float_attr, bool_attr, with_attrs, and the _with level forms), a Format of Text (key=value, quoting what needs it) or Json (one object per line), a Sink (a descriptor, an io.Stream, a line closure or a Record handler), optional RFC 3339 timestamps, and a level from parse_level or the LOG_LEVEL variable. Each record is one write, so lines from green threads do not interleave.
std/termis_tty, size and set_size. enter_raw returns a droppable Raw that restores the terminal when released. Key, read_key (a lone escape resolves after 50 ms) and parse_keys. ANSI helpers: fg, bg with 16, 256 and RGB colours, bold, dim, underline, cursor movement, clear_screen, the alternate screen, strip and visible_width. colour_enabled honours NO_COLOR, CLICOLOR_FORCE and TERM=dumb. open_pty.
std/mimeMedia types by file extension and back (by_extension, extension) for web, image, font, archive, audio, video and subtitle formats. sniff recognises content by its magic bytes or its leading text and falls back to plain text or application/octet-stream.
std/semverSemantic Versioning 2.0.0: parse (with an optional v, failing at the offset of the first bad part), format, and compare and less with prerelease precedence, ignoring build metadata.
std/container/heapA binary Heap[T] ordered by a less function: insert, pop, peek and size.
std/container/lruA least-recently-used Cache[K, V] of fixed capacity: get (refreshes the entry), put (returns the evicted key), contains, size and keys from most to least recent. All run in constant time over index-linked entries.
std/container/dequeA ring-buffer Deque[T]: push_front, push_back, pop_front, pop_back, front, back, at and size, doubling when full.
std/container/setSet[T] over a map, in insertion order: set, from_slice, add and remove (both return whether the set changed), has, size, items, union, intersection, difference and is_subset.
std/container/orderedAn AVL Tree[K, V] for ordered keys: tree, put, get, remove, contains, size, height, is_valid, first, last, floor_entry, ceiling_entry, each, each_range, keys, values, entries and the half-open range(lo, hi).
std/container/sortedSorted[T], an ordered set over ordered.Tree: sorted, from_slice, add, remove, has, size, items, first, last, floor_item, ceiling_item and range.
std/archiveThe filesystem layer shared by std/archive/tar and std/archive/zip. Names are cleaned and rejected when absolute, containing .. or NUL, or passing through a symbolic link below the destination. Files are created exclusively without following links.
std/archive/tarustar, GNU and pax archives. A streaming Reader (next, read_body, read_entry, list) with limits on header, entry and total size. A Writer (add_file, add_dir, add_symlink, add_hardlink, finish) that uses pax records for long or non-ASCII names. gzip through read_gzip and write_gzip. extract, extract_gzip, create and create_gzip over the filesystem strip setuid, setgid and sticky bits.
std/archive/cpionewc, CRC and odc archives, detected per entry on read: a Reader, a Writer (add_file, add_dir, add_symlink, add_links, finish), and extract and create over the filesystem with the safe extraction of std/archive. Hard links store their data with the last link in newc and CRC. The binary format fails with Unsupported.
std/archive/zipZip archives read through the central directory, with zip64, stored and deflate entries, CRC-32 checks and limits on entries, sizes and compression ratio. Written with add_file, add_dir, add_symlink and finish, which emits zip64 records when a count or size needs them. extract works over the filesystem. Encrypted entries and other methods fail with Unsupported.
std/testingT, passed to a test fn(*T), with log, error, fatal, skip, require and sub. Assertions equal, not_equal, equal_slice, is_true, is_false, is_some, is_none, contains, contains_item, close_to, unexpected, must and expect_error render values of any type. table and table_of. run and run_with run each test on its own green thread with a timeout, filter with -run, print with -v and exit with status 1 on failure. bench, bench_for and blackhole. golden rewrites its file when UPDATE_GOLDEN is set. check_property, check_shrunk and check_ints print the seed and shrink integers.
std/base32RFC 4648 base32 with the standard and extended-hex alphabets: encode, encode_unpadded, decode (case-insensitive, padding optional, failing at the first bad character or on an impossible length), encode_hex and decode_hex.
std/base58The Bitcoin alphabet (encode, decode), the Flickr alphabet (encode_flickr, decode_flickr) and Base58Check (encode_check, decode_check), failing at the first bad character.
std/ascii85encode, encode_adobe (with <~ ~>), decode, and Z85 (encode_z85, decode_z85).
std/msgpackMessagePack: the Value model with timestamps and extensions, a decoder with depth and length limits that reports the offset of an error, the smallest-form encode, and serialize[T] and deserialize[T].
std/bsonBSON documents as []Field with ObjectId, datetime, binary, regex, int32, int64, double and Decimal128 (as bytes): decode, encode, get, diagnostic, new_object_id and parse_object_id.
std/iniINI files with sections, = or :, ; and # comments, quoted values, continuations and duplicate keys (last wins, or all with collect): parse, get, get_all, sections, set, format.
std/propertiesJava .properties: parse, get, set, format, with \u escapes and surrogate pairs.
std/bigInt over 32-bit limbs. Parsing and printing in bases 2 to 36 (printing divides the limbs, packed into 64-bit words, by the largest power of the base below 2^64 with a precomputed reciprocal). add, sub, mul (Karatsuba), divmod, divmod_floor, divmod_euclid, pow, modpow (Montgomery for odd moduli), mod_inverse, gcd, lcm, isqrt. Shifts and bitwise operators with two's complement semantics. is_probable_prime, next_prime, random_below, to_f64, from_bytes and to_bytes. Division by zero is an error. Not constant time.
std/big/ratNormalised rationals over big.Int: ratio, parse (a/b, decimals, exponents), the four operations, inv, cmp, to_fixed, to_f64.
std/big/decimalA coefficient and an i32 exponent: exact add, sub and mul, and div and rescale with HalfEven, HalfUp, Down, Up, Floor or Ceiling rounding to a target exponent.
std/redisRESP2 and RESP3 over TCP or TLS: a droppable Client with a ClientHandle, connect with AUTH, SELECT and HELLO 3, command, typed helpers for strings, hashes, lists, sets, sorted sets and publish, pipelining, transaction, pub/sub through a channel usable in select, command timeouts, and limits on bulk size and nesting.
std/smtpAn SMTP client: connect, connect_starttls and connect_tls, EHLO extensions, AUTH PLAIN, LOGIN, XOAUTH2 and CRAM-MD5 (plaintext authentication is refused unless insecure_auth), send with per-recipient results, dot-stuffing, pipelining when advertised, and errors separating 4xx from 5xx.
std/mailMessage building: Message with text and HTML alternatives and attachments, RFC 2047 encoded words, quoted-printable, base64 wrapped at 76, RFC 5322 dates, and rejection of CR and LF in any header.
std/templateA text template engine over a Data model (to_data[T] through serde): {{ expr }}, if, for, include, block and extends, let, trim markers, filters (built in and registered), HTML autoescaping, depth and output limits, and errors with line and column. A Set is read-only while rendering, so green threads share it.
std/multipartmultipart parsing and writing (RFC 7578, RFC 2046): a streaming Reader with limits and a spill sink for large parts, RFC 2231 and 5987 parameters, Writer, Form, and request_form for an http.Request.
std/base64encode and decode, and encode_url and decode_url for the URL-safe alphabet without padding (RFC 4648 §5). The URL-safe decoder rejects padding, other alphabets and non-zero trailing bits.

Resource ownership

Every standard library resource that must be disposed of is a droppable owner bound with using. defer is for work that is not disposal: unlocking a lock, signalling a channel, restoring ambient state and logging.

Networking

Processes

Resilience

Text

Time

Browser automation

TLS

Derived serialization

std/serde defines a Writer and a Reader, structs of closures through which values are written and read. For every concrete type the compiler derives a function that writes a value to a Writer, a function that reads it from a Reader, and a Schema describing it:

std/json, std/orm and std/web are built on these. T.field, where T is a struct type, is a serde.Field[T, F] holding the field's name and index, so a function can take a field of a given struct with a given type.

Data

Unicode

HTML

Regular expressions

Compression

Web