Cheatsheet - all builtins at a glance
Every standard-library function and constant, grouped by library: use it when you know the name and want the library and call shape. Each row's library prefix links to the per-library doc, which is authoritative.
Functions
| Call | What it does |
|---|---|
archive.pack(format, entries) | Bundle a list of archive.Entry into bytes; format "tar"/"zip"/"tar.gz". |
archive.unpack(format, b) | Read a bundle back into a list of archive.Entry (256 MiB / 65536-entry caps; over a cap raises Error{kind:"limit"}). |
archive.unpackWith(format, b, opts) | unpack with caller caps (archive.UnpackOptions{maxTotalBytes, maxEntryBytes, maxEntries, skipSpecial}; 0 = default, math.MAX_INT = unlimited, negative throws). |
asn1.decode(b) / .encode(v) | Parse BER bytes into an opaque asn1.Value / serialise one back to DER bytes. |
asn1.decodeWith(b, o) | decode under lower caps (asn1.DecodeOptions{maxDepth, maxNodes}; 0 = default). |
asn1.typeOf/tagClass/tagNumber/isConstructed(v[, ptr]) | Element type name / class / numeric tag / constructed-ness; pointer tokens are child indices ("/0/2"). |
asn1.get(v[, ptr]) / .has(v, ptr) / .length(v[, ptr]) | Sub-element as asn1.Value / whether a pointer resolves / child count of a constructed node. |
asn1.asInt/asBool/asString/asBytes/asOid/isNull(v[, ptr]) | Read a leaf: integer/enum, boolean, string type or octets, raw octets, dotted OID, or whether NULL. |
asn1.integer/enumerated/boolean/null/octetString(...) | Build a primitive element. |
asn1.utf8String/printableString/ia5String/oid(s) | Build a string / OID element. |
asn1.sequence(items) / .set(items) | Build a constructed element from a list of asn1.Value. |
asn1.tagged(class, n, v) / .retag(class, n, v) | EXPLICIT (wrap) / IMPLICIT (overwrite tag) context/application tagging; class "context"/"application"/... |
binary.bitXor(data, key) / .bitAnd / .bitOr | data XOR / AND / OR key, the key repeated over the data (a short key is a mask); the result has data's length. |
binary.bitNot(data) | Every bit of data inverted. |
binary.concat(a, b) | Join two bytes into a fresh bytes (O(len a + len b); in an accumulation loop use binary.join, or net.readAll/readN for a stream). |
binary.contains(haystack, needle) | Whether needle occurs in bytes haystack (boolean sibling of indexOf). |
binary.endsWith(b, suffix) | True iff bytes b ends with suffix. |
binary.indexOf(haystack, needle [, from [, limit]]) | Byte index of the first needle at/after from (default 0); -1 if absent. limit (default len) bounds the search to [from, limit) so a bounded probe does not overscan. from = idx + 1 makes find-all one O(n) pass. |
binary.join(parts [, sep]) | Concatenate a list of bytes into one bytes in O(n) (optional bytes sep between pieces). The byte-data strings.join. |
binary.make(n [, fill]) | Allocate n bytes each fill (byte 0-255; default 0): the bytes allocator (no literal). n capped at 256 MiB (32 MiB tiny). |
binary.readInt(order, b, offset, size) / .readUint / .readFloat | The signed / unsigned integer (size 1, 2, 4, 8) or float (4, 8) at offset; order "le" / "be". |
binary.readInts(order, b, offset, count, size[, stride]) / .readFloats | count numbers stride bytes apart (default size), as a list; reads one column of a record block. |
binary.split(b, sep) | Split bytes on a non-empty sep -> list of bytes (e.g. a MIME body on its boundary, one Go pass). |
binary.startsWith(b, prefix) | True iff bytes b begins with prefix. |
channel.make(capacity) | New channel of T; capacity 0 = unbuffered, n = buffered. Type from the binding. |
channel.send(ch, value) | Deep-copy value in and send (blocks per capacity); send on a closed channel is a catchable error. |
channel.recv(ch) | Block and return the next value; throws (catchable) on a closed and drained channel. |
channel.recvTimeout(ch, ms) | recv waiting at most ms; else Error{kind: "timeout"}, nothing taken; 0 polls. |
channel.close(ch) | Close the channel; a second close does nothing. Buffered values still drain. |
channel.select(chs) | Fan-in: next value from any open channel; throws when all are closed and drained. |
channel.selectTimeout(chs, ms) | select waiting at most ms; else Error{kind: "timeout"}, nothing taken; 0 polls. |
channel.len(ch) / .capacity(ch) | Buffered value count / buffer capacity. |
compress.discard(stream) | Drop a streaming compressor without returning output; releases its state. A no-op on a finalized or discarded stream. |
compress.finalize(stream) | Close a streaming compressor; returns all compressed bytes. |
compress.pack(algo, b[, level]) | Compress bytes; algo "gzip"/"zlib"/"deflate", optional level "fast"/"default"/"best". |
compress.stream(algo [, level]) | Start a streaming compressor -> compress.Stream. |
compress.unpack(algo, b) / .unpackWith(algo, b, o) | Decompress bytes; output past 256 MiB, or compress.UnpackOptions{maxBytes} (0 = default, math.MAX_INT = none), raises Error{kind:"limit"}. zlib / deflate refuse trailing bytes; gzip reads every member. |
compress.update(stream, b) | Feed one chunk into a streaming compressor. |
convert.fromCodepoint(n) | One-rune string for Unicode code point n (whole range, 1-4 UTF-8 bytes); errors on out-of-range / surrogate. |
convert.toBool(v) | Canonical conversion to bool (0/1, 0.0/1.0, "true"/"false"). |
convert.toCodepoint(char) | Unicode code point (int) of a one-rune string; errors unless exactly one code point (not a grapheme cluster). |
convert.toFloat(v) | Convert to float (int→float, float identity, string parses, bool→1.0/0.0). |
convert.toInt(v [, radix]) | Convert to int (string parses, bool→1/0; a float truncates, deprecated: math.trunc / round / floor / ceil return the int); optional radix 2/8/10/16 for a string of bare digits. |
convert.toString(v) | Convert to string (always succeeds; uses the value's display form). |
convert.typeOf(v) | Runtime kind as string ("int", "float", "string", "bool", "null", "list", "map", "object"). |
convert.objectType(v) | Specific registered name of an opaque object (e.g. "json.Value"); errors on a non-object. |
crc.compute(algo, b) | One-shot checksum. algo is "crc32" or "crc64". Returns big-endian bytes (4 or 8). |
crc.discard($s) | Drop a crc.Stream without computing its checksum; on a finished stream it does nothing. |
crc.finalize($s) | Final checksum as big-endian bytes; consumes the handle (later use: kind "closed"). |
crc.stream(algo) | Allocate a crc.Stream for algo; feed chunks via crc.update then close with crc.finalize. |
crc.update($s, $bytes) | Feed one chunk into a crc.Stream (mutates by side effect). |
crypto.deriveKey(algo, secret, salt, length, crypto.KdfParams) | Every key derivation: "hkdf-<hash>" (info), "pbkdf2-<hash>" (iterations), "argon2id" (time, memoryKiB, threads), "scrypt" (n, r, p); no defaults. |
crypto.encrypt(algo, plaintext, key, nonce, aad) / .decrypt(algo, box, key, nonce, aad) | Authenticated encryption, "aes-gcm" (key 16/24/32 bytes), "chacha20-poly1305" (key 32), both nonce 12, or "xchacha20-poly1305" (key 32, nonce 24) (never reuse one under a key), the 16-byte tag appended. A wrong key / nonce / aad or tampered box is an error. |
crypto.blockEncrypt(algo, data, key, iv) / .blockDecrypt(algo, data, key, iv) | Block modes with no MAC, for interop: "aes-ecb-nopad"/"aes-ecb-pkcs7"/"aes-cbc-nopad"/"aes-cbc-pkcs7"/"aes-ctr"/"aes-cfb"; iv 16 bytes, null for ECB. |
crypto.sign(algo, msg, privateKey) / .verify(algo, msg, sig, publicKey) | "ed25519" (raw keys), "rsa-pkcs1-sha256/384/512" (PKCS#1 v1.5, PEM), "rsa-pss-sha256/384/512" (PSS, salt = hash length, PEM); "rsa-sha*" deprecated, "ecdsa-sha256/384/512" (JOSE R||S, PEM). verify -> bool. RSA / ECDSA default binary only. |
crypto.keypair(algo) / .publicKey(algo, privateKey) | crypto.Keypair{public, private} for "ed25519", "x25519", "mlkem768" (raw bytes), "rsa2048/3072/4096", "p256"/"p384"/"p521" (PEM: PKCS#8 / SEC1 private, PKIX public). |
crypto.agree("x25519", privateKey, peerPublic) | X25519 shared secret (RFC 7748); run it through HKDF (deriveKey). A low-order peer key is an error. |
crypto.encapsulate("mlkem768", publicKey) / .decapsulate("mlkem768", ct, privateKey) | Post-quantum KEM (ML-KEM-768): crypto.Encapsulation{ciphertext, sharedSecret} / the 32-byte secret. Default binary only. |
crypto.wrap(algo, plaintext, publicKey) / .unwrap(algo, ct, privateKey) | RSAES-OAEP key wrapping, "rsa-oaep-sha256" / "rsa-oaep-sha1" with PEM keys (default binary only), or "nacl-sealedbox" with raw X25519 keys (a sealed box anyone can make with the public key). |
crypto.hashPassword(algo, password) / .verifyPassword(password, hash) | Store a password: a self-describing hash string ("argon2id", "bcrypt", "scrypt", fresh salt) / check one in constant time; parameters past the caps are "limit"; password is bytes (encoding.encode("utf-8", s); a string is deprecated) |
crypto.jwkPublic($privPem) / .jwkToPem($jwkJson) / .csr($privPem, domains) | Canonical public JWK JSON (RFC 7638; SHA-256 it for the thumbprint); the inverse jwkToPem (public JWK -> PUBLIC KEY PEM bytes for crypto.verify, so a JWKS kid resolves to a key); DER PKCS#10 CSR over a list of string of domains. For ACME / JWT. Default binary only. |
crypto.mtweiKeygen() | A client EC-SRP keypair (crypto.Keypair: 32-byte private, 33-byte public) for MikroTik MAC-Telnet login. |
crypto.mtweiId(user, password, salt) | The 32-byte EC-SRP validator from the credentials and the router's 16-byte salt. |
crypto.mtweiClientKey(private, serverKey, clientKey, validator) | The 32-byte EC-SRP login proof (RouterOS 6.43+/v7 MAC-Telnet). |
crypto.randBytes(n) | n crypto-grade random bytes (n >= 0). |
crypto.randInt(lo, hi) | Uniform crypto-grade int in the inclusive range [lo, hi] (rejection-sampled, unbiased; unseedable). |
decimal.from(x) | A decimal.Decimal from a decimal string, an int, or a float (by its shortest form: 0.1 -> 0.1). |
decimal.add(a, b) / .sub / .mul | Exact arithmetic; operands may be Decimals, ints or decimal strings. |
decimal.div(a, b[, scale[, mode]]) | Exact quotient, or an error when it has no finite decimal form; with scale, rounded to that many places. |
decimal.round(d, scale[, mode]) | Exactly scale places; modes "half-even" (default) / "half-up" / "half-down" / "up" / "down" / "ceiling" / "floor". |
decimal.compare(a, b) / .sign(d) / .scale(d) / .isInteger(d) | Ordering (-1 / 0 / 1), sign, digits after the point, no fractional part. |
decimal.neg / .abs / .normalize / .pow(d, n) / .sum(xs) | Negate, absolute value, drop trailing zeros, exact integer power, sum of a list. |
decimal.toInt(d) / .toFloat(d) | An exact int (errors on a fraction / overflow); the nearest float. |
decimal.toString(d) | Deprecated (removed in 0.29.0): convert.toString(d) / %v. |
encoding.codecs() | Canonical character-codec names in registration order. |
encoding.decode(codec, b) | Decode bytes from a character codec to a Jennifer string. |
encoding.encode(codec, s) | Encode a Jennifer string into a character codec's bytes. |
encoding.fromText(format, s) | Decode a binary-to-text format. format: "hex", "base32", "base32-hex", "base64", "base64-url", "ascii85", "z85", "quoted-printable", "uri-percent", "uri-form". |
encoding.isAscii(b) | True iff every byte in b is < 0x80. |
encoding.lenBytes(s) | UTF-8 byte length of s (pair with len(s) for rune count). |
encoding.lenRunes(b) | Rune count of valid UTF-8 bytes; errors on invalid UTF-8. |
encoding.parseCookies(header) | A Cookie header -> map of string to string (first of a repeated name wins); > 1000 cookies "limit". |
encoding.parseForm(text) | A form body / query string -> map of string to string; > 10000 pairs "limit", malformed "encoding". |
encoding.parseMultipart(contentType, body) | A multipart/form-data body -> list of encoding.FormPart{name, filename, contentType, data}; capped ("limit"). |
encoding.toText(format, b) | Encode bytes as printable text. format: "hex", "base32", "base32-hex", "base64", "base64-url", "ascii85", "z85", "quoted-printable", "uri-percent", "uri-form". |
fs.appendBytes(path, content) | Append bytes to path; creates the file if missing. |
fs.appendString(path, content) | Append UTF-8 string to path; creates the file if missing. |
fs.chmod(path, mode) | Set permission bits (e.g. 0o600); Unix/Linux. Rejected outside [0, 0o7777]. |
fs.chown(path, uid, gid) | Set owner / group (-1 leaves unchanged); Unix/Linux, usually needs privilege. |
fs.close($f) | Close an fs.File handle; a second close does nothing, other use throws "closed". |
fs.eof($f) | True iff the next read on $f would error or return partial. Sticky. |
fs.exists(path) | True if path resolves; permission errors still surface. |
fs.hasEvent($w) | Whether an fs.Watcher has a queued change event (non-blocking peek). |
fs.isDir(path) | True iff path exists and is a directory. |
fs.isFile(path) | True iff path exists and is a regular file. |
fs.list(path) | Sorted entry names in path. Non-recursive; returns list of string. |
fs.listBytes(path) / .walkBytes(path) | list / walk with names as bytes (list of bytes / list of fs.StatBytes); list / walk throw "fs" on a name that is not UTF-8. |
fs.mkdir(path) | Create a single directory; errors if any parent is missing. |
fs.mkdirAll(path) | Create path and every missing parent (like mkdir -p). |
fs.mkfifo(path[, mode]) | Create a named pipe (default 0600); existing path errors. Unix only. |
fs.next($w) | Block for the next fs.Event (path, kind, isDir) from an fs.Watcher; errors when the watcher is closed. |
fs.open(path, mode) | Open path and return an fs.File. mode: "read", "write", "append". |
fs.readBytes(path) / .readBytes($f, n) | Whole-file read (1 arg) or up to n bytes from handle (2 args). Partial + sticky-EOF on short handle reads. |
fs.readChars($f, n) | Up to n runes from handle, UTF-8 decoded. Partial + sticky-EOF on short reads. |
fs.readLine($f) | One line from handle, \r\n / \n stripped. Errors on EOF; check fs.eof first. |
fs.readSecretBytes(path) / .readSecretString(path) | Read a key / token file, refusing one others could read or replace (OpenSSH-style permission check); over 1 MiB is "limit". |
fs.readString(path) | Whole file as UTF-8; invalid UTF-8 is a positioned runtime error. |
fs.realpath(path) | Absolute, symlink-resolved canonical path (resolve os.ARGS[0] to find files beside the real script). Missing / unresolvable errors. |
fs.readlink(path) | A symlink's target, verbatim (not resolved; use fs.realpath to resolve). Non-symlink / missing errors. |
fs.symlink(target, linkPath) | Create a symlink at linkPath pointing to target (like ln -s target linkPath). Existing linkPath errors. |
fs.remove(path) | Delete one file or empty directory. Non-empty dir errors. |
fs.removeAll(path) | Recursive delete; a separate verb so the risky call is visible. |
fs.rename(old, new) | Same-filesystem rename; cross-fs is a boundary error. |
fs.stat(path) | Returns fs.Stat (path, size, isDir, mtimeNanos, mode). Missing path errors. |
fs.sync($f) | Flush a write/append handle's data to the storage device (fsync); handle stays open. The "safe to remove the stick" step. |
fs.walk(path) | Depth-first, sorted, includes path. Returns list of fs.Stat. Skips symlinks; unreadable subdirectories are not descended. |
fs.watch(path) / .watchWith(path, fs.WatchOptions{intervalMs}) | Watch a file / dir (recursive) for changes -> fs.Watcher (intervalMs 0 = ~300 ms, else >= 20); pull with fs.next / fs.hasEvent, stop with fs.close. watch(path, intervalMs) deprecated. |
fs.writeBytes(path, content) / .writeBytes($f, b) | Whole-file overwrite (path form) or write via handle (fs.File form). |
fs.writeString(path, content) / .writeString($f, s) | Whole-file overwrite (path form) or write via handle (fs.File form). |
fs.writeNew(path, content) | Create path with content, failing (catchable) if it exists (O_EXCL). Atomic test-and-set for a file lock. |
fs.makeTempFile([dir[, prefix[, suffix]]]) | Create a unique empty file (atomic, 0600); returns its path. dir="" = system temp; parent must exist. |
fs.makeTempDir([dir[, prefix]]) | Create a unique directory (atomic, 0700); returns its path. Only the leaf is created (not mkdir -p). |
gpio.open(path) / .close(chip) / .setup(chip, pin, direction) | Open a gpiochip -> gpio.Chip / release its lines and close it / request line pin with gpio.IN / gpio.OUT. Linux only. |
gpio.read(chip, pin) / .write(chip, pin, value) / .release(chip, pin) | Read a line (0/1) / drive an output line / free it. The pin-only forms and gpio.chip are deprecated. |
hash.compute(algo, b) | One-shot digest. algo is "md5", "sha1" (both non-cryptographic), "sha256", "sha384", "sha512", "sha3-224/256/384/512", "blake2b-256/384/512" or "blake2s-256". Returns raw bytes. |
hash.hmac(algo, message, key) | Keyed-hash MAC (RFC 2104) over the same algorithms; raw bytes out. For JWT / TOTP / SigV4 / webhook signatures. |
hash.equal(a, b) | Constant-time equality of two bytes (for MAC / token / digest checks); false on a length or content difference. |
hash.discard($s) | Drop a hash.Stream without computing its digest; releases its state. A no-op on a finalized or discarded stream. |
hash.finalize($s) | Final digest as bytes; consumes the handle (later calls error). |
hash.stream(algo) | Allocate a hash.Stream for algo; feed chunks via hash.update then close with hash.finalize. |
hash.update($s, $bytes) | Feed one chunk into a hash.Stream (mutates by side effect). |
httpd.listen(addr) / .listenWith(addr, opts) | Start an HTTP server -> httpd.Server; httpd.Options{maxBodyBytes, maxInFlight, respondTimeoutMs, bodyTimeoutMs, writeTimeoutMs, maxHeaderBytes, dirListing, followSymlinks, etag, certPem, keyPem} (certPem + keyPem: HTTPS; etag: content-hash ETags from serveFile / serveDir; 0 = default). listenTLS / listenTLSWith deprecated. |
httpd.setMaxBufferBudget(bytes) | Move the process-wide memory-guard ceiling (default 4 GiB) listenWith enforces; raise it for a big-RAM host, lower it for a small one (floored at 10 MiB). |
httpd.setMaxBufferBudgetFromRAM(fraction) | Opt-in, cgroup-aware: set the budget to fraction of the detected machine limit (min of host RAM and cgroup limit) -> the bytes set; errors if undeterminable. |
httpd.address($srv) / .shutdown($srv) | Bound address of a server / graceful drain (unblocks parked accept). |
httpd.maxInFlight($srv) | The server's in-flight request limit (bound a serve loop's workers to it). |
httpd.accept($srv) | Block for the next request -> httpd.Request (the pull loop). Errors once the server is shut down. Throws "closed" once the server is shut down. |
httpd.method($req) / .path($req) / .query($req, name) / .rawQuery($req) / .header($req, name) / .body($req) / .remoteAddr($req) | Read the accepted request (query / header -> "" if absent; rawQuery = the query string as sent, no ?; body -> bytes). |
httpd.requestValue($req, key) / .setRequestValue($req, key, value) | Read / write a request-scoped note ("" if unset); scratch space to memoize a value computed once per request, never sent to the client. |
httpd.setHeader($req, name, value) / .respond($req, status, body) | Set a response header / send the response once (body is string or bytes). |
httpd.isOpen($req) / .timedOut($req) | bool: the request still awaits its answer / the engine answered 503 itself after the respond timeout. |
httpd.etag($req, tag) | Set the ETag and honour a conditional GET -> bool (true = a 304 was sent, stop; handles If-None-Match list / * / W/). |
httpd.serveFile($req, path) / .serveDir($req, root) | Answer with a file / the file under root for the request path (.. cannot escape root). |
httpd.serveFileEtag($req, path) / .serveDirEtag($req, root) | Deprecated (removed in 0.29.0): serveFile / serveDir on a server with httpd.Options{etag: true}. |
i2c.open(path, addr) | Open an I2C bus and select 7-bit slave addr -> i2c.Bus. Linux only. |
i2c.read($bus, n) / .write($bus, data) | Read n raw bytes / write raw bytes to the selected slave. |
i2c.readReg($bus, reg, n) / .writeReg($bus, reg, data) | Register read (set pointer, read back) / register write. |
i2c.writeRead($bus, data, n) | Write data, then read exactly n bytes in one combined transfer (repeated START, no STOP). |
i2c.close($bus) | Close the bus. |
images.decode(data) / .decodeWith(data, o) | Decode PNG / JPEG / GIF bytes -> images.Image; over 64 Mpx (8 Mpx on jennifer-tiny), or images.DecodeOptions{maxPixels}, raises Error{kind:"limit"} from the header alone. |
images.info(data) | Format and size from the header without decoding -> images.Info{format, width, height}. |
images.encode(format, img[, quality]) | Encode to "png" / "jpeg" (quality 1..100, default 90) / "gif" -> bytes. |
images.create(w, h[, color]) | A new image filled with color (default transparent). |
images.fromPixels(w, h, data) / .pixels(img) | Build from / export raw RGBA bytes, 4 per pixel, row by row. |
images.width(img) / .height(img) | The size in pixels. |
images.pixel(img, x, y) | One pixel -> images.Color{r, g, b, a}. |
images.colorPixels(img) / .alphaPixels(img) | Export the RGB bytes (3 per pixel, alpha left out) / the alpha byte of each pixel, row by row. |
images.rgb(r, g, b) / .hex(s) / images.Color{r, g, b, a} | Build an images.Color; hex takes "#rgb" / "#rrggbb" / "#rrggbbaa"; a literal's omitted a is 0. .rgba is deprecated. |
images.crop(img, x, y, w, h) | A rectangle inside the image. |
images.resize(img, w, h[, filter]) | Scale; 0 for one side keeps the aspect; filter "catmullrom" (default) / "bilinear" / "nearest". |
images.fit(img, maxW, maxH[, filter]) | Shrink to fit the box, keeping the aspect; never enlarges. |
images.rotate(img, degrees) / .flip(img, direction) | Turn by a multiple of 90 clockwise / mirror "horizontal" or "vertical". |
images.grayscale(img) / .threshold(img, level) / .dither(img) | Luminance / black-and-white at a level / black-and-white by Floyd-Steinberg. |
images.fill(img, x, y, w, h, color) / .draw(dst, src, x, y) | Paint a rectangle / composite one image onto another, alpha-blended and clipped. |
intl.formatNumber(locale, value, digits) | An int / float / decimal.Decimal with exactly digits (0-20) fraction digits, half-even, in the locale's CLDR separators and grouping. |
intl.load(lang, catalog) | Merge a map of string to string into the catalog for lang; the first language loaded is the default. |
intl.setLocale(lang) / .locale() | Set / read the current locale (e.g. "de-AT"; locale() is "" until set); setLocale needs a loaded catalog for the tag or its language. |
intl.tr(key[, params]) | Translate key (fallback: locale -> base language -> default -> the key); params (a map) fills %name% placeholders (%% escapes a literal %). |
io.eof() | True if and only if the next io.readLine() would error. Pair with while (not io.eof()) {...}. |
io.readBytes(n) / .readChars(n) | Up to n bytes / runes from stdin (fewer at end of input). |
io.printf(format, args...) | Format-string write to stdout. Verbs: %d %f %s %t %v %a %%; per-verb |key=value modifiers (pad, prec, base, null=*, ...). |
io.eprintf(format, args...) | Like printf, but writes to stderr (diagnostics / logs that must not mix into stdout). |
io.readLine() | Read one line from stdin (trailing newline stripped). Errors at EOF; check io.eof() first. |
io.readLine(prompt) | Same as io.readLine() but writes prompt to stdout first. |
io.readLines() | Slurp all remaining stdin lines into a list of string (newlines stripped, LF/CRLF, OS-independent). Use the readLine loop for large streams. |
io.sprintf(format, args...) | Like printf, but returns the string. Same verbs and |key=value modifiers. |
len(v) (language built-in) | Structural length: rune count (string), element count (list), entry count (map), byte count (bytes). |
json.decode(s) | Parse JSON text into an opaque json.Value handle (walk it with the accessors below). |
json.decodeWith(s, opts) | decode under lower caps: json.DecodeOptions{maxDepth, maxNodes} (0 keeps a default). |
json.encode(v) | Compact JSON string for an encodable value (struct/map -> object, bytes -> base64, json.Value round-trips; task / non-string keys error). |
json.encodePretty(v) | Like encode, 2-space indented. |
json.encodeWith(v, opts) | encode with a json.EncodeOptions{indent, sortKeys, rawHtml, canonical}; canonical is RFC 8785 (for signing / hashing). |
json.mergePatch(target, patch) | RFC 7386 merge patch: patch objects merge, a null member removes, anything else replaces. Returns a new json.Value. |
json.typeOf(v[, ptr]) | JSON type at an optional JSON Pointer: null bool int float string list map, or missing. |
json.get(v[, ptr]) | Sub-node at a JSON Pointer, as a json.Value (walk stays opaque; no pointer = the node itself). |
json.has(v, ptr) | Whether the JSON Pointer resolves to an existing node. |
json.keys(v[, ptr]) | list of string keys of the addressed map, in document order. |
json.length(v[, ptr]) | Element count of a list / entry count of a map at the pointer. |
json.asInt(v[, ptr]) / asFloat / asString / asBool | Extract the addressed leaf as a typed value (strict; asFloat promotes an integral number). |
json.asFloats(v[, ptr]) / asInts / asStrings | Read a whole list as list of float / int / string in one call, each element as the single reader does. |
json.isNull(v[, ptr]) | Whether the addressed node is JSON null. |
json.map() / .list() | A fresh empty JSON map / list json.Value: the explicit start of a document (writes never auto-vivify). |
json.map(m) / .list(xs) | A JSON map / list json.Value built from a Jennifer map / list in one step (linear; json.Value elements shared). |
json.set(v, ptr, val) | Non-mutating: upsert a map key or replace an in-range list index; returns a new json.Value. Strict (no missing intermediates). |
json.insert(v, ptr, val) | Insert into a list before index ptr (or - = at end); returns a new handle. |
json.append(v, ptr, val) | Push onto the list addressed by ptr (sugar for insert at /.../-). |
json.remove(v, ptr) | Drop the map key or list element at ptr; returns a new handle. |
json.move(v, from, to) | Relocate the subtree at from to to (read, remove, then set). |
kv.open() | A fresh in-memory kv.Store (reset each run). |
kv.openFile(path) | A kv.Store persisted to path (survives across runs; flush per mutation). |
kv.set(store, key, value, ttl) | Store value, expiring in ttl seconds (0 = never). |
kv.add(store, key, value, ttl) | Store only if absent; whether it stored (bool). |
kv.get(store, key) | The value, or "" when absent / expired. |
kv.has(store, key) | Whether the key is present and unexpired (bool). |
kv.keys(store[, prefix]) | The unexpired keys, sorted, optionally only those with prefix (list of string). |
kv.delete(store, key) | Remove the key; whether it existed (bool). |
kv.touch(store, key, ttl) | Re-arm the expiry; whether it existed (bool). |
kv.incr(store, key, delta) | Add signed delta; the new value (an absent key starts at 0 and is created, without TTL). |
kv.setValue(store, key, value, ttl) / .getValue(store, key) | Store / read an opaque library value (json.Value, ...), shared not copied; in-memory stores only; getValue errors when absent. |
kv.close(store) | Close this handle (a second close does nothing; other use: "closed"). |
linalg.dot(a, b) / .distance(a, b) | Dot product / Euclidean distance of vectors (list of float) -> float. Length-checked. |
linalg.cross(a, b) / .normalize(v) | 3-D cross product of length-3 vectors / the unit vector v / norm(v) (zero vector errors) -> list of float. |
linalg.norm(x) | L2 norm of a vector, or the Frobenius norm of a matrix -> float (polymorphic). |
linalg.scale(x, s) / .add(a, b) / .sub(a, b) | Scalar multiply / element-wise sum / difference of a vector or a matrix (same shape). |
linalg.matmul(a, b) | General product: matrixmatrix -> matrix; matrixvector or vectormatrix -> vector; vectorvector errors (use dot). |
linalg.transpose(m) / .trace(m) | Transpose of a list of list of float / trace (diagonal sum, square) -> float. |
linalg.determinant(m) | Determinant of a square matrix -> float (singular is 0). |
linalg.inverse(m) / .solve(a, b) | Matrix inverse / solve a x = b; a singular matrix is a catchable error. |
linalg.identity(n) / .zeros(r, c) / .shape(m) | The n x n identity / an r x c zero matrix / [rows, cols] of a matrix (list of int). |
lists.all(xs, fn) | True if the func fn(x) is true for every element (true for empty). Short-circuits. |
lists.any(xs, fn) | True if the func fn(x) is true for any element. Short-circuits. |
lists.concat(a, b) | New list with a's elements followed by b's. |
lists.contains(xs, item) | True if item appears in xs (haystack, needle). |
lists.indexOf(xs, item) | Index of the first element equal to item, or -1 (haystack, needle). |
lists.filter(xs, fn) | New list of the elements where the func fn(x) returns true. |
lists.find(xs, fn) | First element where the func fn(x) is true; errors (catchable) if none. |
lists.first(xs) | Element at index 0. Empty input errors. |
lists.last(xs) | Element at the last index. Empty input errors. |
lists.map(xs, fn) | New list of fn(x) for each element (fn a func); result type checked at the binding. |
lists.mismatch(a, b [, from]) | First index at/after from (default 0) where the two lists differ (value, or only one has an element); -1 if none. One native scan for "what changed". |
lists.push(xs, item) | New list with item appended. |
lists.range(start, end, step) | Half-open list of ints stepping by step; end excluded; step must match direction (a..b for step 1). |
lists.reduce(xs, fn, init) | Fold left with the func fn(acc, x), starting from init. |
lists.replicate(xs, n) | New list of n copies of xs concatenated (replicate([false], $n)); elements are deep copies. |
lists.reverse(xs) | New list with elements reversed. |
lists.shuffle(xs) | Fisher-Yates; respects math.randSeed. Non-mutating. |
lists.sort(xs) | New ascending-sorted list. Numeric / string / bool elements; mixed errors. |
lists.sortBy(xs, keyFn) | New list sorted ascending by the key the func keyFn(x) returns (a comparable scalar). |
lists.sortWith(xs, cmp) | New list sorted stably by the func cmp(a, b) -> int (< 0: a first, > 0: b first, 0: equal). For orders on several keys. |
maps.delete(m, key) | New map without key. Missing key errors (strict at boundaries). |
maps.has(m, key) | True if map m contains key. The non-erroring companion to $m[key]. |
maps.keys(m) | List of keys in insertion order. |
maps.merge(a, b) | New map; b's entries layered on top of a. |
maps.values(m) | List of values in insertion order. |
maps.without(m, keys) | New map without every key in the list keys (one copy). Missing key errors. |
meta.hasCapability(name) | Whether the build includes capability name ("net" / "exec" / "sql"; another name throws); the # pragma-jennifer-capability: set (bool). |
meta.call(name, args...) | Invoke a top-level function by runtime name (arity + types checked); errors / exit propagate. |
meta.defined(name) | Whether a top-level function name exists (bool). |
meta.callMain(name, args...) / .definedMain(name) | Like call / defined but against the entry program's functions (a module reaching its host's handlers). |
ml.linearRegression(X, y) / .ridge(X, y, alpha) | Fit OLS / L2-ridge regression -> ml.Model (regressor). |
ml.kNN(X, y, k) / .naiveBayes(X, y) | Fit a k-NN / Gaussian naive-Bayes classifier -> ml.Model. |
ml.logisticRegression(X, y) / .logisticRegressionWith(X, y, ml.LogisticOptions{learningRate, epochs}) | Fit a binary (0/1) logistic classifier (gradient descent) -> ml.Model. |
ml.decisionTree(X, y) / .randomForest(X, y), ...With(X, y, ml.TreeOptions{maxDepth} / ml.ForestOptions{nTrees, maxDepth}) | Fit a CART tree / bagged forest classifier -> ml.Model. |
ml.kMeans(X, k) / .kMeansWith(X, k, ml.KMeansOptions{maxIter}) | Fit k-means clustering (k-means++ seed) -> ml.Model. Uses math.randSeed. |
ml.pca(X, nComponents) | Fit PCA (covariance eigendecomposition) -> ml.Model (transform). |
ml.standardScaler(X) / .minMaxScaler(X) | Fit a z-score / [0,1] feature scaler -> ml.Model (transform). |
ml.predict(model, X) | Predicted labels (int, classifier/cluster) or values (float, regressor) per row. |
ml.transform(model, X) / .predictProba(model, X) | Transform features (scaler/PCA) / positive-class probability (logistic). |
ml.free(model) | Deprecated no-op (removed in 0.29.0): a model is a value the GC frees. |
ml.trainTestSplit(X, y, testFraction) | Shuffle + split -> ml.Split{trainX,trainY,testX,testY}. Uses math.randSeed. |
ml.kFold(nSamples, k) | k contiguous CV folds -> list of ml.Fold{trainIdx, testIdx}. |
ml.accuracy(yTrue, yPred) | Fraction of exact matches. |
ml.precision/recall/f1(yTrue, yPred [, positive]) | Binary classification metrics for the positive label (default 1). |
ml.confusionMatrix(yTrue, yPred) | ml.Confusion{labels, matrix} (rows=true, cols=predicted). |
ml.rocAuc(yTrue, scores) | Binary ROC-AUC from 0/1 labels and predicted scores (tie-aware). |
ml.rmse/mae/r2(yTrue, yPred) | Regression error metrics (r2 = coefficient of determination). |
ml.lasso(X, y, alpha) | Fit L1-regularized regression (coordinate descent; sparse coefficients) -> ml.Model. |
ml.kNNRegressor(X, y, k) / .decisionTreeRegressor(X, y [, maxDepth]) | Regression variants of k-NN / CART (predict a continuous value). |
ml.randomForestRegressor(X, y) / .randomForestRegressorWith(X, y, ml.ForestOptions{nTrees, maxDepth}) | Bagged regression trees -> ml.Model (regressor). |
ml.coefficients(model) / .intercept(model) | Read a linear/logistic model's learned weights / bias. |
ml.centroids(model) / .components(model) / .explainedVariance(model) | k-means centres / PCA axes / PCA per-component variance ratios. |
ml.featureImportances(model) | Gini feature importances of a tree / forest (sum to 1). |
ml.polynomialFeatures(X, degree) | Expand X to all monomials up to degree (+ bias); stateless. Degree in [1,8]. |
ml.mse(yTrue, yPred) / .logLoss(yTrue, probas) | Mean-squared error / binary cross-entropy. |
math.abs(x) | Absolute value of x (int→int, float→float). |
net.abort($conn) | Close a TCP connection with a reset (RST) instead of an orderly close; for tests and fakes. |
net.accept($listener) | Block until a client connects to $listener; return the new net.Conn. |
net.address($h) | Polymorphic. Conn -> peer address; Listener / UDPSocket -> local bound address. |
net.close($h) | Polymorphic. Closes a net.Conn, net.Listener, or net.UDPSocket. |
net.connect(address) | TCP client: dial "host:port" and return a net.Conn, within the default 30 s. |
net.connectWith(address, net.ConnectOptions) | Connect with options: timeoutMs (0 = 30 s, math.MAX_INT = none), tls, tlsOptions. |
net.connectTLS(address[, net.TLSOptions]) | TLS client: dial "host:port" + handshake within the default 30 s, verifying the cert against the host. net.TLSOptions for caCert / skipVerify. |
net.startTLS($conn[, net.TLSOptions]) | Upgrade an open plaintext net.Conn to TLS in place (STARTTLS) within the default 30 s; host reused from connect; same handle. |
net.startTLSWith($conn, net.ConnectOptions) | startTLS with the options' timeoutMs and tlsOptions. |
net.listen(address) | Bind TCP "host:port" (use ":0" for ephemeral). Returns a net.Listener. |
net.listenUDP(address) | Bind a UDP socket. Returns a net.UDPSocket; usable as both client and server. |
net.lookup(host) | DNS: resolve host to a list of string IPs, within the default 30 s. |
net.lookupWith(host, net.LookupOptions) | lookup within the options' timeoutMs; with dnsServers, ask those DNS servers only (no hosts file, no search list). |
net.readAll($conn [, maxBytes]) | Read to EOF, returning the whole stream as one bytes in a single Go loop (whole-body / object download). maxBytes>0 caps (catchable). |
net.readBytes($conn, n) | Read up to n bytes; blocks for at least one byte. Empty bytes once the peer closed (sticky EOF). |
net.readN($conn, n) | Read exactly n bytes for a length-prefixed frame; a close before n bytes is a catchable error, not a truncated return. |
net.recvFrom($sock, n) | Block for one UDP datagram, up to n bytes. Returns net.Datagram{data, peer, truncated} (truncated: it was longer than n). |
net.reverseLookup(ip) | Reverse DNS: IP address to a list of string of hostnames. |
net.reverseLookupWith(ip, net.LookupOptions) | reverseLookup within the options' timeoutMs. |
net.sendTo($sock, peer, bytes) | Send one UDP datagram to peer ("host:port"). |
net.setBroadcast($sock, on) | Enable/disable SO_BROADCAST so a sendTo may target a broadcast address. Off by default; Linux/Unix only. |
net.bindToDevice($sock, iface) | Pin a UDP socket's egress/ingress to one interface via SO_BINDTODEVICE ("" clears). The multi-homed-host fix a wildcard bind can't give. Linux-only; unprivileged on 5.7+ for an unbound socket, else CAP_NET_RAW. |
net.setIdleTimeout($conn, ms) | Fail a read after ms without a byte, re-armed per underlying read (0 clears); a steady transfer is never cut. With a read deadline, the first to pass fires. |
net.setReadDeadline($conn, ms) | Arm a read deadline ms ms out (0 clears). The poll-with-timeout primitive: a read past it throws kind: "timeout"; writes stay usable. |
net.setWriteDeadline($conn, ms) | Arm a write deadline ms ms out (0 clears). Bounds a slow send; reads untouched. |
net.writeBytes($conn, bytes) | Blocking write of every byte to a net.Conn. |
regex.escape(s) | Escape RE2 metacharacters so s matches literally when used as a pattern. |
regex.find(pattern, s) | First match as regex.Match; sentinel with start=-1 if no match. |
regex.findAll(pattern, s) | Every non-overlapping match; returns list of regex.Match. |
regex.matches(pattern, s) | True iff pattern matches somewhere in s. |
regex.replace(pattern, s, replacement) | Replace every match. $1, ${name} expand to captured groups; $$ is a literal $. |
regex.split(pattern, s) | Split s at every match; returns list of string. |
serial.open(path, baud) / .openWith(path, opts) | Open a serial port (raw 8N1, or full serial.Options) -> serial.Port. Linux only. |
serial.read($port, n) / .write($port, data) | Read up to n bytes (blocks for >=1; a parity error: kind "serial") / write all bytes (-> null). |
serial.flush($port) / .close($port) | Discard buffered I/O / close the port. |
serial.setReadDeadline($port, ms) / .setWriteDeadline($port, ms) | Arm (or with 0 clear) a read / write deadline; past it the call throws kind "timeout". |
spi.open(path) / .openWith(path, spi.Options{mode, speedHz, bitsPerWord}) | Open an SPI device -> spi.Device (defaults mode 0, 500 kHz, 8 bits; configure deprecated). Linux only. |
spi.transfer($dev, data) / .close($dev) | Full-duplex exchange (out and in together) / close the device. |
sql.open(driver, dsn) / .openWith(driver, dsn, sql.Options{allowInsecure, queryTimeoutMs}) / .close($c) | Open a MySQL / Postgres connection -> sql.Connection / close it. Verified TLS to another host; a weaker DSN mode needs allowInsecure. Default binary only. |
sql.query(target, sql, params...) / .exec(target, sql, params...) | Query -> sql.Rows / statement -> sql.Result{affected, lastId}. target = Connection or Tx; params bind through placeholders. |
sql.next($rows) / .columns($rows) / .closeRows($rows) | Advance the cursor (false at end) / column names / close early. |
sql.asInt / .asFloat / .asString / .asBool / .asBytes($rows, col) / .isNull($rows, col) | Read the current row's column (name or index), typed; a NULL column is an error (check isNull). |
sql.begin($c) / .commit($tx) / .rollback($tx) | Transaction: begin -> sql.Tx (a query/exec target), then commit / rollback. |
sql.setQueryTimeout(ms) | Deprecated (removed in 0.29.0): use sql.Options.queryTimeoutMs. The process-wide deadline of connections opened with queryTimeoutMs 0. |
sql.prepare($c, sql) / .queryStmt($s, ...) / .execStmt($s, ...) / .closeStmt($s) | Prepared-statement lifecycle. |
math.acos(x) | Arccosine (radians); errors outside [-1, 1]. |
math.acosh(x) | Inverse hyperbolic cosine; errors for x < 1. |
math.asin(x) | Arcsine (radians); errors outside [-1, 1]. |
math.asinh(x) | Inverse hyperbolic sine. |
math.atan(x) | Arctangent (radians). |
math.atan2(y, x) | Two-argument arctangent, quadrant-aware (radians). |
math.atanh(x) | Inverse hyperbolic tangent; errors outside (-1, 1). |
math.beta(a, b) | Beta function B(a,b)=gamma(a)gamma(b)/gamma(a+b); a, b > 0. |
math.cbrt(x) | Real cube root (handles negatives). |
math.ceil(x) | Smallest int >= x. Accepts int (identity) or float. |
math.comb(n, k) | Binomial coefficient nCr (exact int); k>n is 0; errors on overflow. |
math.cos(x) | Cosine (radians). |
math.cosh(x) | Hyperbolic cosine; errors on overflow. |
math.erf(x) | Error function. |
math.erfc(x) | Complementary error function (1 - erf). |
math.exp(x) | e^x; errors on overflow. |
math.expm1(x) | e^x - 1, accurate for small x. |
math.factorial(n) | n! (exact int); errors on negative n or overflow (n > 20). |
math.floor(x) | Largest int <= x. Accepts int (identity) or float. |
math.gamma(x) | Gamma function; errors at the poles (0, negative ints) and on overflow. |
math.gcd(a, b) | Greatest common divisor (non-negative; gcd(0,0)=0). |
math.hypot(x, y) | sqrt(x^2 + y^2) without intermediate overflow. |
math.lbeta(a, b) | Natural log of the beta function, ln B(a,b); a, b > 0. |
math.lcm(a, b) | Least common multiple (lcm(x,0)=0); errors on overflow. |
math.lgamma(x) | ln|gamma(x)|; errors at the poles. |
math.ln(x) | Natural logarithm; errors for x <= 0. |
math.log(x, base) | Logarithm of x to an arbitrary base; errors for non-positive x/base or base 1. |
math.log10(x) | Base-10 logarithm; errors for x <= 0. |
math.log1p(x) | ln(1 + x), accurate for small x; errors for x <= -1. |
math.log2(x) | Base-2 logarithm; errors for x <= 0. |
math.max(a, b) | Larger of two numbers; mixed int/float promotes to float. |
math.min(a, b) | Smaller of two numbers; mixed int/float promotes to float. |
math.perm(n, k) | k-permutations of n (nPr, exact int); k>n is 0; errors on overflow. |
math.pow(x, y) | x raised to y; always float. Errors on NaN/Inf-producing inputs. |
math.rand() | Float in [0, 1) from the shared seedable (non-crypto) source. |
math.randInt(lo, hi) | Int in [lo, hi] inclusive; errors if lo > hi. |
math.randSeed(n) | Reseed the shared source for reproducible runs (also drives lists.shuffle; uuid / password use crypto instead). |
math.regBetaI(x, a, b) | Regularized incomplete beta I_x(a,b) in [0,1] (CDF engine for beta / t / F / binomial); 0<=x<=1, a,b>0. |
math.regGammaP(a, x) | Regularized lower incomplete gamma P(a,x) in [0,1] (gamma / chi-square CDF); a>0, x>=0. |
math.regGammaQ(a, x) | Regularized upper incomplete gamma Q(a,x) = 1 - P(a,x). |
math.round(x) | Round to nearest int (half away from zero). |
math.sign(x) | -1 / 0 / 1 with the sign of x, preserving its type (int -> int, float -> float). |
math.sin(x) | Sine (radians). |
math.sinh(x) | Hyperbolic sine; errors on overflow. |
math.sqrt(x) | Square root; always float. Errors on negative input. |
math.tan(x) | Tangent (radians). |
math.tanh(x) | Hyperbolic tangent. |
math.trunc(x) | Round toward zero -> int; int argument is the identity. |
os.flag(name) | Deprecated (removed in 0.29.0): use the args module. |
os.getEnv(name) | Read environment variable name. Unset → empty string, no error. Non-UTF-8 value throws "os". |
os.getEnvBytes(name) | The raw value as bytes (unset → empty). |
os.argsBytes() | os.ARGS as list of bytes. |
os.setEnv(name, value) | Set environment variable name for this process (and children it spawns). Invalid name errors. |
os.unsetEnv(name) | Remove environment variable name (not the same as setting it to ""); no-op when unset. |
os.hasEnv(name) | Whether name is set, even to "" (bool). |
os.hasFlag(name) | Deprecated (removed in 0.29.0): use the args module. |
os.isTerminal(stream) | Is stream ("stdout"/"stderr"/"stdin") an interactive terminal? Pipe/file -> false. |
os.cwd() | Absolute path of the current working directory. |
os.homeDir() | Current user's home directory ($HOME / %USERPROFILE%). |
os.tempDir() | Temp-file directory ($TMPDIR//tmp; %TMP% on Windows). Never errors. |
os.catchSignal(name) / .gotSignal(name) | Opt into trapping a Unix signal ("int"/"term"/"hup"/"usr2") / poll-and-clear whether it arrived. Cooperative; "usr1" reserved for kill -USR1 diagnostics. |
os.kill(p) | Send SIGTERM to spawned process $p. |
os.poll(p) | True if spawned process $p has exited (a following os.wait returns immediately). |
os.release(p) | Drop a finished process handle from the registry (frees captured output); errors if $p still runs. |
os.run(argv) | Blocking: run argv to completion, return os.Result{exitCode, stdout, stderr}. |
os.runBytes(argv) | Like run, returns os.BytesResult{exitCode, stdout, stderr as bytes, truncated} for binary output. |
os.spawn(argv) / .spawnWith(argv, os.SpawnOptions{stdout, stderr}) | Non-blocking: start argv, return an os.Process; each stream "" (capture), "inherit", "discard" or a path. The options-map form is deprecated. |
os.wait(p) | Block until spawned process $p exits; return os.Result. Idempotent. |
os.waitTimeout(p, ms) / .waitBytesTimeout(p, ms) | wait / waitBytes waiting at most ms; else "timeout", the child keeps running; 0 polls. |
os.waitBytes(p) | Like wait, returns os.BytesResult. Either form may read the same handle. |
path.base(p) | Last element of p. "" -> ".", "/" -> "/". OS-aware; not a filename sanitizer. |
path.dir(p) | All but the last element of p, cleaned. "c.txt" -> ".". |
path.ext(p) | File extension incl. the leading dot (".txt"), or "". |
path.stem(p) | Base name of p without its extension. |
path.join(a, b, ...) | Join >= 1 elements with the separator and clean; empty elements dropped. Portable alternative to hardcoding "/". |
path.clean(p) | Shortest path equivalent to p (collapses ., .., repeated separators). "" -> ".". |
path.isAbs(p) | Whether p is absolute (bool). |
path.split(p) | [dir, file] where dir keeps its trailing separator, so dir + file == p. |
stats.mean(xs) / .median(xs) | Arithmetic mean / median of a list of int|float -> float. Empty errors. |
stats.variance(xs) / .stddev(xs) | Population variance / standard deviation -> float. |
stats.sampleVariance(xs) / .sampleStddev(xs) | Sample (Bessel n-1) variance / stddev -> float. Needs >= 2 elements. |
stats.mad(xs) | Median absolute deviation (robust spread) -> float. |
stats.skewness(xs) / .kurtosis(xs) | Shape: population skewness / excess kurtosis (normal -> 0) -> float. Non-constant, >= 2. |
stats.percentile(xs, p) | The p-th percentile (p in [0,100], linear interpolation) -> float. |
stats.quartiles(xs) / .iqr(xs) | [Q1,Q2,Q3] (list of float) / interquartile range p75-p25 (float). |
stats.min(xs) / .max(xs) / .range(xs) | Smallest / largest element / spread max-min; all preserve int/float kind. Empty errors. |
stats.sum(xs) | Sum: int for an all-int list (overflow-checked), float otherwise; sum([]) is 0. |
stats.geometricMean(xs) / .harmonicMean(xs) | Geometric / harmonic mean -> float. Every element must be > 0. |
stats.weightedMean(xs, ws) | Weighted mean sum(x*w)/sum(w) -> float. Equal length; weights not summing to 0. |
stats.zscore(xs) | Each element standardized (x-mean)/stddev -> list of float. Constant list errors. |
stats.mode(xs) (elem) / .modes(xs) (list) | Most frequent element / every tied modal value; both preserve kind. |
stats.correlation(xs, ys) / .covariance(xs, ys) | Pearson correlation ([-1,1]) / population covariance of two equal-length lists -> float. |
stats.sampleCovariance(xs, ys) | Sample (n-1) covariance -> float. Needs >= 2 elements. |
stats.describe(xs) | One-call stats.Summary{count, min, q1, median, mean, q3, max, stddev}. |
stats.normalPdf/normalCdf/normalQuantile(p,mean,sd) | Normal density / CDF / inverse-CDF; sd>0, quantile p in (0,1). |
stats.normalSample(mean, sd) | One Normal(mean, sd) draw (uses math.randSeed). |
stats.tCdf(x, df) / .tQuantile(p, df) / .tPdf(x, df) | Student's t CDF / inverse / density; df>0. |
stats.chiSquareCdf(x, df) / .chiSquareQuantile(p, df) | Chi-square CDF / inverse; x>=0, df>0. |
stats.fCdf(x, df1, df2) / .fQuantile(p, df1, df2) | F CDF / inverse; x>=0, dfs >0. |
stats.binomialPmf(k, n, p) / .binomialCdf(k, n, p) | Binomial mass / CDF; k,n ints, 0<=p<=1. |
stats.poissonPmf(k, lambda) / .poissonCdf(k, lambda) | Poisson mass / CDF; k int, lambda>0. |
stats.linearRegression(xs, ys) | Simple OLS -> stats.Regression{slope, intercept, r, r2, stdErr, pValue, n}. |
stats.multipleRegression(X, ys) | Deprecated (removed in 0.29.0): ml.linearRegression + ml.intercept / ml.coefficients (same numbers). |
stats.confidenceInterval(data, level) | t-based CI for the mean -> stats.Interval{lower, upper}; level in (0,1). |
stats.proportionCi(method, successes, n, level) | Binomial-proportion CI; method "wald"/"wilson"/"clopper-pearson" -> stats.Interval. |
stats.tTest(data, mu) / .tTest2(a, b) | One-sample / two-sample (Welch) t-test -> stats.Test{statistic, df1, df2, pValue}. |
stats.chiSquareTest(observed, expected) | Chi-square goodness of fit -> stats.Test; expected counts >0. |
stats.fTest(a, b) / .anova(groups) | Two-sided F-test of variances / one-way ANOVA -> stats.Test. |
stats.histogram(data, binEdges) | Bin counts as NumPy histogram: k+1 ascending edges -> k counts (list of int), bins [e_i, e_i+1), the last closed; values outside are dropped. |
strings.chars(s) | Split s into a list of string, one entry per Unicode code point. |
term.makeRaw(stream) / .restore(state) | Enter / leave raw mode (unbuffered, no-echo) on a terminal ("stdin"); makeRaw returns a single-use term.State. Non-terminal errors. |
term.size(stream) | The terminal's term.Size{rows, cols} (query "stdout"). Errors (catchable) off a terminal or when no window size is set; fall back. |
term.readByte() | Next raw byte from stdin (0-255); throws "closed" at end of input. Bytes, not decoded keys. Refused in the REPL. |
term.readByteTimeout(ms) | As readByte, but throws "timeout" when no byte arrives within ms (0 polls). Tells a lone Escape from an escape sequence. Refused in the REPL. |
testing.assertContains(hay, needle) | Throw Error{kind:"assertion"} unless hay contains needle: substring / list element / map key. |
testing.assertEqual(actual, expected) | Throw unless deeply equal (lists / maps / structs compare by value). |
testing.assertFalse(cond) | Throw unless cond (a bool) is false. |
testing.assertNotEqual(actual, expected) | Throw unless not deeply equal. |
testing.assertThrows(name, kind) | Throw unless the named zero-arg function throws an Error of that kind. |
testing.assertThrowsArgs(name, args, kind) | As assertThrows, binding the list args to the function's parameters (no per-case wrapper function). |
testing.assertTrue(cond) | Throw unless cond (a bool) is true. |
testing.report(format, results) | Render results to "text", "tap", or "junit" (returns string). |
testing.reset() | Clear the process-wide result accumulator. |
testing.results() | Snapshot of the accumulator as list of testing.Result. |
testing.run(name) | Invoke a zero-arg user function by name; catch every failure mode into a testing.Result. |
testing.runArgs(name, args) | Like run, binding the args list to the function's parameters (arity + type checked). |
strings.contains(s, sub) | True if s contains the substring sub. |
strings.count(s, sub) | Number of non-overlapping occurrences of a non-empty sub in s. |
strings.endsWith(s, suffix) | True if s ends with suffix. |
strings.fold(s) | Remove common Latin diacritics for a sort / search key (Österreich -> Osterreich); case preserved. Not full Unicode collation. |
strings.indexOf(s, sub [, from]) | Rune index of first sub in s at/after from (default 0), or -1. |
strings.lastIndexOf(s, sub) | Rune index of the last sub in s, or -1 if absent. |
strings.join(parts, sep) | Concatenate list of string parts separated by sep. Inverse of strings.split. |
strings.lower(s) | Lowercase s (Unicode-aware). |
strings.replicate(s, n) | n non-negative copies of s concatenated. |
strings.replace(s, old, new) | Replace all occurrences of old in s with new. |
strings.split(s, sep) | Split s on non-empty sep; returns list of string. |
strings.startsWith(s, prefix) | True if s starts with prefix. |
strings.trim(s) | Strip leading and trailing Unicode whitespace. |
strings.trimLeft(s) | Strip leading whitespace. |
strings.trimRight(s) | Strip trailing whitespace. |
strings.trimPrefix(s, prefix) / .trimSuffix(s, suffix) | s without the exact affix, removed once; s unchanged when it does not carry it. |
strings.trimSet(s, cutset) / .trimLeftSet / .trimRightSet | Strip leading and/or trailing runes that occur in cutset (trimRightSet("1.500", "0") -> 1.5). |
strings.upper(s) | Uppercase s (Unicode-aware). |
task.allocatedBytes() | Bytes the calling task's allocation budget has counted (0 without one). |
task.cancel($t) | Request cooperative cancellation of $t; the body stops at its next loop checkpoint. Non-blocking. |
task.cancelled() | Non-raising poll: true if the current spawn body has been cancelled (false on main). |
task.discard($t) | Mark a task of T fire-and-forget; suppresses exit-time loud-fail. Returns null. |
task.setAllocBudget(bytes) | Opt-in: count what the calling task (and tasks it spawns) allocates; past bytes throws "limit". math.MAX_INT lifts. |
task.poll($t) | True if $t has finished (non-blocking). |
task.wait($t) | Block until $t finishes; return its value or re-raise its error. |
task.waitAll($ts) | Block for all tasks in $ts; results in list order; re-raises the first error if any. |
task.waitAllTimeout($ts, ms) | Like waitAll, but throws Error{kind: "timeout"} if not all finish within ms; the tasks keep running. |
task.waitAny($ts) | Block until any task in $ts is done; return its index. |
task.waitAnyTimeout($ts, ms) | Like waitAny, but throws a catchable Error{kind: "timeout"} if none finishes within ms. |
task.waitTimeout($t, ms) | Like wait, but throws a catchable Error{kind: "timeout"} if $t doesn't finish within ms. |
time.add($t, $d) | time.Time shifted by duration $d. |
time.after($a, $b) | True if $a is strictly later than $b. |
time.before($a, $b) | True if $a is strictly earlier than $b. |
time.day($t) | Day of month, 1-31. |
time.equal($a, $b) | True if $a and $b are the same UTC instant. |
time.format($t, layout) | Strftime-style format. Codes: %Y %m %d %H %I %p %M %S %z %a %A %b %B %j %u %%; numeric ones take |pad=N (%d|pad=0 unpadded). |
time.fromHours(n) | time.Duration of n hours. |
time.fromIso(s) | Parse RFC 3339; accepts Z or +HH:MM; optional fractional seconds. |
time.fromMilliseconds(n) | time.Duration of n milliseconds. |
time.fromMinutes(n) | time.Duration of n minutes. |
time.fromSeconds(n) | time.Duration of n seconds. |
time.fromUnix(seconds) | time.Time at the given Unix second. |
time.fromUnixMilliseconds(ms) | time.Time at the given Unix millisecond. |
time.fromUnixNanos(ns) | time.Time at the given Unix nanosecond. |
time.hour($t) | Hour 0-23. |
time.hours($d) | Span as whole hours (int). |
time.inZone($t, $z) | Re-render $t in $z's wall-clock; UTC instant is preserved. |
time.iso($t) | RFC 3339 string: Z for UTC, +HH:MM otherwise; fractional seconds when non-zero. |
time.local() | Host's current time.Zone (name + offset). |
time.milliseconds($d) | Span as whole milliseconds (int). |
time.minute($t) | Minute 0-59. |
time.minutes($d) | Span as whole minutes (int). |
time.month($t) | Calendar month, January = 1. |
time.nanosecond($t) | Fractional second, 0-999_999_999. |
time.now() | Current instant in the host's local zone (time.Time). |
time.parse(s, layout) | Strict strftime-style parse. Same code set as format (%j / %u are format-only). |
time.second($t) | Second 0-59. |
time.seconds($d) | Span as whole seconds (int). |
time.sleep($d) | Block the running task for $d. Zero returns at once; negative throws "runtime". Returns null. |
time.sub($a, $b) | Signed time.Duration between two time.Time values. |
time.unix($t) | Unix-second instant of $t (int). |
time.unixMilliseconds($t) | Unix-millisecond instant of $t (int). |
time.unixNanos($t) | Unix-nanosecond instant of $t (int). |
time.utc() | Current instant in UTC (time.Time). |
time.weekday($t) | ISO 8601 weekday: Monday = 1 ... Sunday = 7. |
time.year($t) | Calendar year (int). |
time.zone(offset, name) | Build a time.Zone from an integer offset (seconds east of UTC) and a display name. |
toml.decode(s) | Parse TOML text into an opaque toml.Value handle (walk it with the accessors below). |
toml.decodeWith(s, o) | decode under lower caps (toml.DecodeOptions{maxDepth, maxNodes}; 0 = default). |
toml.encode(v) / .encodePretty(v) | TOML string for a toml.Value (or native map / list / scalar); encodePretty blank-lines sections. Null value / non-table root errors. |
toml.typeOf(v[, ptr]) | Node type at an optional JSON Pointer: null bool int float string list map datetime, or missing. |
toml.get(v[, ptr]) | Sub-node at a JSON Pointer, as a toml.Value (walk stays opaque; no pointer = the node itself). |
toml.has(v, ptr) | Whether the JSON Pointer resolves to an existing node. |
toml.keys(v[, ptr]) / .length(v[, ptr]) | list of string table keys in document order / element count of a list or table. |
toml.asInt(v[, ptr]) / asFloat / asString / asBool | Extract the addressed leaf as a typed value (strict; asFloat promotes an int). |
toml.asFloats(v[, ptr]) / asInts / asStrings | Read a whole list as list of float / int / string in one call, each element as the single reader does. |
toml.asDatetime(v[, ptr]) / .isDatetime(v[, ptr]) / .asLocal(v[, ptr]) | An offset date-time as a time.Time (needs use time;) / whether the node is one / a local date-time, date or time as toml.Local{year, month, day, hour, minute, second, nanosecond}. |
toml.map() / .list() | A fresh empty table / array toml.Value: the explicit start of a document (writes never auto-vivify). |
toml.map(m) / .list(xs) | A table / array toml.Value built from a Jennifer map / list in one step (linear; toml.Value elements shared). |
toml.set(v, ptr, val) / .insert / .append / .remove / .move | Non-mutating edits by JSON Pointer; each returns a new toml.Value (strict / no missing intermediates). |
uuid.v4() | A new random (version 4) UUID. |
uuid.v7() | A new time-ordered (version 7) UUID. |
uuid.isValid(s) | Whether s is a well-formed UUID string. |
uuid.parse(s) | The 16 bytes of a UUID string; errors on malformed input. |
uuid.version(s) | Version digit (4, 7, ...; 0 for NIL); errors on malformed input. |
xml.decode(s) / .decodeWith(s, o) | Parse XML into an opaque xml.Value (root element); errors with line / column on malformed or not namespace-well-formed input. xml.DecodeOptions{maxDepth, maxNodes, namespaces} lowers the caps; namespaces (prefix -> URI) seeds bindings for a fragment. |
xml.encode(v) / .encodePretty(v) | Serialize an xml.Value (compact / 2-space indented). |
xml.typeOf(node) | "element" or "text". |
xml.tag(node) | The element's tag name as written (with prefix). |
xml.localName(node) / .namespace(node) | The tag without its prefix / the element's namespace URI ("" for none). |
xml.lookupPrefix(node, prefix) | The namespace URI bound to prefix at the element; errors when unbound. |
xml.attrNS(node, uri, local) | The attribute named (uri, local), whatever its prefix; errors if absent. xml.hasAttrNS(node, uri, local) tests presence. |
xml.text(node) | The element's concatenated direct character data (or a text node's string). |
xml.attr(node, name) | An attribute value; errors if absent. xml.hasAttr(node, name) tests presence. |
xml.attrs(node) | The attribute names (list of string, document order). |
xml.children(node) | The element children (list of xml.Value; text excluded). |
xml.get(node, path[, ns]) | First element matching an XPath-style path (name/name[k]/*/*:local, /-separated); errors if none. ns (prefix -> URI) makes p:name match by namespace. |
xml.findAll(node, path[, ns]) | Every element matching the path (list of xml.Value). xml.has(node, path[, ns]) -> bool. |
xml.element(name) | A fresh empty element xml.Value (namespace-unaware: name as written). |
xml.elementNS(uri, qname) | A fresh empty element in namespace uri; encode declares the prefix where needed. |
xml.setAttr(node, name, value) | The element with the attribute added/updated (fresh handle). |
xml.setAttrNS(node, uri, qname, value) | The element with the namespaced attribute added/updated (fresh handle). |
xml.setText(node, s) | The element with its children replaced by one text node (fresh handle). |
xml.append(parent, child) | The parent element with child appended (fresh handle). |
yaml.decode(s) / .decodeAll(s) | Parse one YAML document (multi-doc errors) / every document of a --- stream (list of yaml.Value), into opaque handles. |
yaml.decodeWith(s, o) | decode under lower caps (yaml.DecodeOptions{maxDepth, maxNodes}; 0 = default). |
yaml.encode(v) / .encodePretty(v) | YAML string for a yaml.Value (or native map / list / scalar): flow (compact) vs block (readable) style. |
yaml.typeOf(v[, ptr]) | Node type at an optional JSON Pointer: null bool int float string bytes list map datetime, or missing. |
yaml.get(v[, ptr]) | Sub-node at a JSON Pointer, as a yaml.Value (walk stays opaque; no pointer = the node itself). |
yaml.has(v, ptr) | Whether the JSON Pointer resolves to an existing node. |
yaml.keys(v[, ptr]) / .length(v[, ptr]) | list of string map keys in document order / element count of a list or map. |
yaml.asInt(v[, ptr]) / asFloat / asString / asBool / isNull | Extract the addressed leaf as a typed value (strict; asFloat promotes an int) / test for null. |
yaml.asFloats(v[, ptr]) / asInts / asStrings | Read a whole list as list of float / int / string in one call, each element as the single reader does. |
yaml.asDatetime(v[, ptr]) / .isDatetime(v[, ptr]) | A timestamp node as a time.Time (needs use time;) / whether the node is a timestamp. |
yaml.asBytes(v[, ptr]) | A !!binary node as bytes. |
yaml.map() / .list() | A fresh empty mapping / sequence yaml.Value: the explicit start of a document (writes never auto-vivify). |
yaml.map(m) / .list(xs) | A mapping / sequence yaml.Value built from a Jennifer map / list in one step (linear; yaml.Value elements shared). |
yaml.set(v, ptr, val) / .insert / .append / .remove / .move | Non-mutating edits by JSON Pointer; each returns a new yaml.Value (strict / no missing intermediates). |
Constants
| Name | Type | Value |
|---|---|---|
math.E | float | Euler's number, 2.718281828459045. |
math.MAX_INT | int | The largest int, 9223372036854775807; an option's "none". |
math.MIN_INT | int | The smallest int, -9223372036854775808. |
math.PI | float | π, 3.141592653589793. |
math.TAU | float | τ = 2π, the full-turn constant, 6.283185307179586. |
meta.BUILD | string | Which Go toolchain compiled the interpreter: "go" / "tinygo". |
meta.VERSION | string | The interpreter's build version (e.g. "0.27.0"). |
meta.SYSMODDIR | string | Resolved system module directory (--sysmoddir > JENNIFER_SYSMODDIR > build default). |
meta.CAPABILITIES | list of string | Host capabilities this build has, sorted: ["exec", "net", "sql"] (standard) / [] (tiny). |
os.ARCH | string | CPU architecture: "amd64", "arm64", "wasm", ... |
os.ARGS | list of string | Argv. Index 0 is the script path, the rest are user args. Reading it throws "os" if an argument is not UTF-8 (os.argsBytes() for raw). |
os.DIRSEP | string | Path-component separator: "/" Unix, "\\" Windows. |
os.EOL | string | Platform line ending. "\n" Unix-likes, "\r\n" Windows. |
os.NCPU | int | Logical CPUs usable by the process (runtime.NumCPU). 1 on jennifer-tiny (single-thread scheduler). |
os.PATHSEP | string | PATH-list separator: ":" Unix, ";" Windows. |
os.PLATFORM | string | OS tag: "linux", "darwin", "windows", ... |
time.PROGRAM_START | time.Time | Captured the moment the time library installed; "since program launched" anchor. |
time.UTC | time.Zone | Canonical UTC: Zone{offset: 0, name: "UTC"}. |
uuid.NIL | string | The all-zero UUID 00000000-0000-0000-0000-000000000000. |
Type-conversion calls
int, float, string, bool, bytes are type keywords (used in def x as int) and never appear in expression position, not even followed by (: int("42") is a parse error pointing at convert.toInt("42"). Use convert.toInt / toFloat / toString / toBool (and encoding.encode("utf-8", s) for bytes). See convert.md for the naming detail.
Removed in 0.28.0
| Removed | Use |
|---|---|
strings.substring, lists.slice / head / tail / pop, binary.slice | Slices: $s[a..b], $xs[0..n] |
strings.repeat | strings.replicate |
two-bound lists.range(a, b) | a..b (or lists.range(a, b, -1) to count down) |
convert.bytesFromString / stringFromBytes | encoding.encode / encoding.decode |
convert.toString(n, radix) | io.sprintf("%d|base=16", n) |
crypto.hkdf / pbkdf2 / argon2id / scrypt | crypto.deriveKey |
testing.runWith / assertThrowsWith | testing.runArgs / assertThrowsArgs |
io.printf($v) with one non-string value | io.printf("%v", $v) |
jennifer lint reports each leftover call (L302).
See also
- index.md - library catalog with code samples and the organizing principles; it links every per-library reference page.
- ../user-guide/imports.md - how to import a library in a Jennifer source file.