Standard library
std/prelude
The prelude: available in every Gojo file without an import.
The prelude: available in every Gojo file without an import. It holds the
methods of the built-in types (str, String, slices, Vec, Map, ?T,
T ! E, rc, Mutex, channels...), the error interface, panic and
assert, and a few general types: Set, Arena, Hasher, Span.
Functions without a body are implemented by the compiler or runtime.
Types: enum Ordering, enum Flow, interface error, interface Number, interface Integer, struct Atomic, struct RwLock, struct Chan, struct Hasher, struct Id, struct Arena, struct Span, struct Set, struct Tuple2, struct Tuple3, struct Tuple4, struct Tuple5, struct Tuple6
Functions: panic, assert, assertEq, unreachable, drop, swap, replace, take, min, max, setOf
Methods on other types: extend ?T, extend T ! E, extend str, extend String, extend []T, extend []String, extend Vec[T], extend Map[K, V], extend Rc[T], extend Weak[T], extend Arc[T], extend Cell[T], extend Mutex[T], extend Sender[T], extend Receiver[T], extend Task[T], extend Iso[T], extend Scope, extend MutexRef[T]
Types
enum Ordering
pub enum Ordering { Less, Equal, Greater }The result of comparing two values: a.compare(b).
enum Flow
pub enum Flow { Continue, Break }Control signal for push-style iteration.
interface error
pub interface error {
fn message(self) -> String
}The built-in error interface, for application-level error handling.
interface Number
pub interface Number {
~int | ~i8 | ~i16 | ~i32 | ~u8 | ~u16 | ~u32 | ~u64 | ~f32 | ~f64
}Numeric types, for generic arithmetic.
interface Integer
pub interface Integer {
~int | ~i8 | ~i16 | ~i32 | ~u8 | ~u16 | ~u32 | ~u64
}Integer types, for Atomic.
struct Atomic
pub unsafe send struct Atomic[T: Integer] {
// and private fields
}An integer that tasks share and change without a lock: each operation is atomic and sequentially consistent. Tasks borrow it and call its methods at the same time:
let hits = Atomic(0)
par for r in requests { if r.ok { _ = hits.add(1) } }Atomic.new
pub fn new(x: T) -> Atomic[T]Atomic.load
pub fn load(self) -> TThe value now.
Atomic.store
pub fn store(self, x: T)Replaces the value.
Atomic.add
pub fn add(self, d: T) -> TAdds d, wrapping around on overflow, and gives the new value.
Atomic.sub
pub fn sub(self, d: T) -> TSubtracts d, wrapping around on overflow, and gives the new value.
Atomic.swap
pub fn swap(self, x: T) -> TReplaces the value and gives the old one.
Atomic.compareSwap
pub fn compareSwap(self, old: T, new: T) -> boolReplaces the value with new if it is old; true if it did.
Atomic.clone
pub fn clone(self) -> Atomic[T]A new Atomic with the value now.
struct RwLock
pub unsafe send struct RwLock[T: send] {
// and private fields
}A lock that many readers may hold at once, or one writer:
let cache = RwLock(Map[String, String]{})
with c = cache.read() { ... } // shared: other readers too
with c = cache.write() { ... } // exclusiveLike Mutex.lock, read and write are projections: the reference can't
leave the block. A writer waiting keeps new readers out, so writers don't
starve.
RwLock.new
pub fn new(x: sink T) -> RwLock[T]RwLock.read
pub fn read(self) yield &TShared access.
RwLock.write
pub fn write(self) yield inout TExclusive access.
RwLock.toString
pub fn toString(self) -> String"RwLock" (the value can't be read without the lock).
struct Chan
pub struct Chan[T] {
// The sending end; `.clone()` it for more senders.
pub tx: Sender[T]
// The receiving end; `.clone()` it for more receivers.
pub rx: Receiver[T]
}Chan[T](n) makes a channel with room for n values (Chan[T](): none, so
a send waits for a receiver). Its two ends are handed out separately:
let ch = Chan[Job](16)
go produce(ch.tx) // the channel closes when the last sender is dropped
for job in ch.rx { run(job) }struct Hasher
pub struct Hasher {
// and private fields
}Computes the hash of values (FNV-1a over u64 words), for writing a
custom hash method.
Hasher.writeU64
pub fn writeU64(inout self, x: u64)Mixes x into the hash.
Hasher.write
pub fn write[T: hash](inout self, x: T)Mixes in the hash of any hashable value.
struct Id
pub copy struct Id[T] {
// and private fields
}A handle to a value in an Arena[T].
struct Arena
pub struct Arena[T] {
// and private fields
}Storage for graphs, trees and other structures whose nodes refer to each
other: nodes are values in the arena, references are Ids. An Id carries
a generation, so one whose value was removed finds nothing, rather than a
different value that took its slot.
var a = Arena[Node]{}
let root = a.alloc(Node{name: "root"})
with n = a.getMut(root) { ... }Arena.alloc
pub fn alloc(inout self, v: sink T) -> Id[T]Stores v and returns its Id.
Arena.get
pub fn get(self, id: Id[T]) yield ?&TThe value for id, if it is still there.
Arena.getMut
pub fn getMut(inout self, id: Id[T]) yield ?inout TThe value for id, to change in place.
Arena.remove
pub fn remove(inout self, id: Id[T]) -> ?TRemoves and returns the value for id; its slot is reused, with a new
generation.
Arena.len
pub fn len(self) -> intThe number of values stored.
struct Span
pub copy struct Span {
pub lo: int
pub hi: int
}A range of byte offsets into a string. A zero-copy parser keeps the owned
input and Spans into it, and borrows views on demand: no reference is
ever stored in a struct.
Span.of
pub fn of(self, s: str) -> strThe part of s the span covers.
Span.len
pub fn len(self) -> intThe length in bytes.
struct Set
pub struct Set[T: hash] {
// and private fields
}A set of values, kept in the order they were first inserted.
var seen = Set[String].new()
if seen.insert(name.clone()) { ... first time ... }Set.new
pub fn new() -> Set[T]An empty set.
Set.insert
pub fn insert(inout self, x: sink T) -> boolAdds x; false if it was there already.
Set.remove
pub fn remove(inout self, x: T) -> boolTakes x out; false if it wasn't there.
Set.contains
pub fn contains(self, x: T) -> boolWhether x is in the set.
Set.len
pub fn len(self) -> intThe number of values.
Set.isEmpty
pub fn isEmpty(self) -> boolWhether the set is empty.
Set.clear
pub fn clear(inout self)Removes every value.
Set.each
pub fn each(self, body: fn(&T) -> Flow)for x in set
Set.toVec
pub fn toVec(self) -> Vec[T] where T: cloneCopies of the values, in insertion order.
Set.union
pub fn union(self, other: Set[T]) -> Set[T] where T: cloneWhat is in either.
Set.intersection
pub fn intersection(self, other: Set[T]) -> Set[T] where T: cloneWhat is in both.
Set.difference
pub fn difference(self, other: Set[T]) -> Set[T] where T: cloneWhat is in this one but not in other.
struct Tuple2
pub struct Tuple2[A, B] {
pub _0: A
pub _1: B
}Tuples: (A, B) is a Tuple2[A, B], (a, b) builds one and t.0 reads
its first element. They are copy when their elements are.
struct Tuple3
pub struct Tuple3[A, B, C] {
pub _0: A
pub _1: B
pub _2: C
}struct Tuple4
pub struct Tuple4[A, B, C, D] {
pub _0: A
pub _1: B
pub _2: C
pub _3: D
}struct Tuple5
pub struct Tuple5[A, B, C, D, E] {
pub _0: A
pub _1: B
pub _2: C
pub _3: D
pub _4: E
}struct Tuple6
pub struct Tuple6[A, B, C, D, E, F] {
pub _0: A
pub _1: B
pub _2: C
pub _3: D
pub _4: E
pub _5: F
}Functions
panic
pub fn panic(msg: str) -> neverEnds the program with msg and the caller's location (exit code 2). Panics
cannot be caught; deferred code does not run.
assert
pub fn assert(cond: bool)Panics unless cond holds.
assertEq
pub fn assertEq[T: comparable](a: T, b: T)Panics unless a == b, showing both values.
unreachable
pub fn unreachable() -> neverMarks code that can't run; panics if it does.
drop
pub fn drop[T](x: sink T)Explicitly end the lifetime of a value.
swap
pub fn swap[T](a: inout T, b: inout T)Exchanges two places.
replace
pub fn replace[T](dst: inout T, value: sink T) -> TPuts value into dst and returns what was there.
take
pub fn take[T: default](dst: inout T) -> TTakes the value out of dst, leaving the type's default ("", 0, none,
an empty Vec...).
min
pub fn min[T: copy + ordered](a: T, b: T) -> TThe smaller of two values (a when they are equal).
max
pub fn max[T: copy + ordered](a: T, b: T) -> TThe larger of two values (a when they are equal).
setOf
pub fn setOf[T: hash](xs: sink Vec[T]) -> Set[T]A set of the values in xs (duplicates once, in the order first seen).
Methods on other types
extend ?T
?T.isSome
pub fn isSome(self) -> boolWhether there is a value.
?T.isNone
pub fn isNone(self) -> boolWhether there is no value.
?T.unwrap
pub fn unwrap(sink self) -> TThe value; panics on none. Prefer ??, if let or try where none can
happen.
?T.expect
pub fn expect(sink self, msg: str) -> TThe value; panics with msg on none.
?T.unwrapOr
pub fn unwrapOr(sink self, d: sink T) -> TThe value, or d (which is evaluated either way; x ?? d evaluates d only
when needed).
?T.map
pub fn map[U](self, f: fn(T) -> U) -> ?Uf applied to the value, if there is one.
extend T ! E
T ! E.isOk
pub fn isOk(self) -> boolWhether this is a value rather than an error.
T ! E.isErr
pub fn isErr(self) -> boolWhether this is an error.
T ! E.unwrap
pub fn unwrap(sink self) -> TThe value; panics with the error. Prefer try or catch.
T ! E.expect
pub fn expect(sink self, msg: str) -> TThe value; panics with msg and the error.
T ! E.unwrapOr
pub fn unwrapOr(sink self, d: sink T) -> TThe value, or d on an error (which is dropped).
T ! E.ok
pub fn ok(sink self) -> ?TThe value, or none on an error.
T ! E.err
pub fn err(sink self) -> ?EThe error, or none.
extend str
str.len
pub fn len(self) -> intThe length in bytes (UTF-8). Indexes and slices count bytes too.
str.ptr
pub fn ptr(self) -> *u8raw pointer to the bytes, for FFI
str.isEmpty
pub fn isEmpty(self) -> boolWhether the length is 0.
str.contains
pub fn contains(self, sub: str) -> boolWhether sub occurs in the string (the empty string always does).
str.startsWith
pub fn startsWith(self, prefix: str) -> boolWhether the string begins with prefix.
str.endsWith
pub fn endsWith(self, suffix: str) -> boolWhether the string ends with suffix.
str.find
pub fn find(self, sub: str) -> ?intThe byte index of the first occurrence of sub.
str.trim
pub fn trim(self) -> strThe string without leading and trailing ASCII whitespace (space, tab, newline, carriage return, vertical tab, form feed). A view: no copy.
str.trimStart
pub fn trimStart(self) -> strThe string without leading ASCII whitespace.
str.trimEnd
pub fn trimEnd(self) -> strThe string without trailing ASCII whitespace.
str.split
pub fn split(self, sep: str) -> Vec[String]The pieces between occurrences of sep: "a,,b".split(",") is
["a", "", "b"], and "".split(",") is [""]. An empty sep splits into
characters.
str.lines
pub fn lines(self) -> Vec[String]The lines, without their \n or \r\n; no empty last line for a trailing
newline.
str.fields
pub fn fields(self) -> Vec[String]The words between runs of ASCII whitespace: " a b\tc ".fields() is
["a", "b", "c"].
str.toUpper
pub fn toUpper(self) -> StringA copy with ASCII letters in upper case (other characters unchanged).
str.toLower
pub fn toLower(self) -> StringA copy with ASCII letters in lower case (other characters unchanged).
str.toString
pub fn toString(self) -> StringAn owned copy.
str.repeat
pub fn repeat(self, n: int) -> StringThe string n times (empty for n <= 0).
str.replace
pub fn replace(self, from: str, to: str) -> StringA copy with every occurrence of from replaced by to (unchanged when
from is empty).
str.bytes
pub fn bytes(self) -> []byteThe bytes, as a view.
str.runes
pub fn runes(self) -> Vec[rune]The Unicode code points. A byte that isn't part of valid UTF-8 (strings
made with String(bytes) or read from files aren't checked) reads as
U+FFFD.
str.compare
pub fn compare(self, other: str) -> OrderingByte-wise order, which is also code-point order.
str.parseInt
pub fn parseInt(self) -> ?intThe decimal integer that is the whole string (an optional + or -, then
digits), or none: no spaces, no other characters, nothing out of range.
str.parseFloat
pub fn parseFloat(self) -> ?f64The floating-point number that is the whole string, or none. Accepts what C's
strtod does: 1.5, -2e10, inf, nan, 0x1p3.
extend String
String.push
pub fn push(inout self, t: str)Appends t. (s += t does the same.)
String.pushRune
pub fn pushRune(inout self, r: rune)Appends the UTF-8 encoding of r; U+FFFD for a value that isn't a Unicode
scalar value (a surrogate, negative, or above U+10FFFF).
String.clear
pub fn clear(inout self)Makes the string empty, keeping its buffer.
String.asStr
pub fn asStr(self) -> strThe string as a view.
extend []T
[]T.len
pub fn len(self) -> intThe number of elements.
[]T.reverse
pub fn reverse(inout self)Reverses the order in place. Only an inout []T (or a range of a
var Vec or array, v[a..b]) can be changed.
[]T.swap
pub fn swap(inout self, i: int, j: int)Exchanges elements i and j; panics when either is out of range.
[]T.sort
pub fn sort(inout self) where T: orderedSorts in ascending order. Stable; O(n log n).
[]T.sortBy
pub fn sortBy(inout self, less: fn(T, T) -> bool)Sorts by less(a, b): true when a goes before b. Stable.
[]T.ptr
pub fn ptr(self) -> *Traw pointer to the first element, for FFI
[]T.isEmpty
pub fn isEmpty(self) -> boolWhether there are no elements.
[]T.get
pub fn get(self, i: int) yield ?&TElement i, or none when i is out of range (indexing with xs[i]
panics instead).
[]T.first
pub fn first(self) yield ?&TThe first element, if any.
[]T.last
pub fn last(self) yield ?&TThe last element, if any.
[]T.contains
pub fn contains(self, x: T) -> bool where T: comparableWhether some element equals x.
[]T.indexOf
pub fn indexOf(self, x: T) -> ?int where T: comparableThe index of the first element equal to x.
[]T.map
pub fn map[U](self, f: fn(T) -> U) -> Vec[U]f applied to each element, in order.
[]T.filter
pub fn filter(self, keep: fn(T) -> bool) -> Vec[T] where T: cloneCopies of the elements for which keep is true.
[]T.each
pub fn each(self, f: fn(T))Calls f on each element, in order.
[]T.any
pub fn any(self, f: fn(T) -> bool) -> boolWhether f is true for some element (stops at the first).
[]T.all
pub fn all(self, f: fn(T) -> bool) -> boolWhether f is true for every element (stops at the first false).
[]T.count
pub fn count(self, f: fn(T) -> bool) -> intHow many elements f is true for.
[]T.fold
pub fn fold[A](self, init: sink A, f: fn(sink A, T) -> A) -> ACombines the elements from the left: f(f(f(init, x0), x1), x2).
[]T.sum
pub fn sum(self) -> T where T: NumberThe sum (0 for no elements). Integer overflow panics, as with +.
[]T.min
pub fn min(self) -> ?T where T: copy + orderedThe smallest element, or none for no elements.
[]T.max
pub fn max(self) -> ?T where T: copy + orderedThe largest element, or none for no elements.
[]T.toVec
pub fn toVec(self) -> Vec[T] where T: cloneAn owned copy.
extend []String
[]String.join
pub fn join(self, sep: str) -> StringThe strings with sep between them: ["a", "b"].join(", ") is "a, b".
extend Vec[T]
Vec[T].push
pub fn push(inout self, x: sink T)Appends x.
Vec[T].pop
pub fn pop(inout self) -> ?TRemoves and returns the last element, or none when empty.
Vec[T].insert
pub fn insert(inout self, i: int, x: sink T)Inserts x at index i (0 <= i <= len()), moving the later elements
up; panics otherwise.
Vec[T].remove
pub fn remove(inout self, i: int) -> TRemoves and returns element i, moving the later elements down; panics when
i is out of range.
Vec[T].swapRemove
pub fn swapRemove(inout self, i: int) -> TRemoves and returns element i, putting the last element in its place:
O(1), but changes the order. Panics when i is out of range.
Vec[T].clear
pub fn clear(inout self)Removes (and drops) every element, keeping the buffer.
Vec[T].truncate
pub fn truncate(inout self, n: int)Keeps the first n elements and drops the rest; nothing happens when n
=
len(). Panics whennis negative.
Vec[T].extend
pub fn extend(inout self, other: sink Vec[T])Moves the elements of other to the end.
Vec[T].reverse
pub fn reverse(inout self)Reverses the order in place.
Vec[T].swap
pub fn swap(inout self, i: int, j: int)Exchanges elements i and j; panics when either is out of range.
Vec[T].sort
pub fn sort(inout self) where T: orderedSorts in ascending order. The sort is stable (equal elements keep their order) and takes O(n log n) time.
Vec[T].sortBy
pub fn sortBy(inout self, less: fn(T, T) -> bool)Sorts by less(a, b): true when a goes before b. Stable.
Vec[T].reserve
pub fn reserve(inout self, n: int)Makes room for n more elements without reallocating; panics ("capacity
overflow") for an impossible size.
Vec[T].cap
pub fn cap(self) -> intThe number of elements there is room for.
extend Map[K, V]
Map[K, V].len
pub fn len(self) -> intThe number of entries.
Map[K, V].isEmpty
pub fn isEmpty(self) -> boolWhether there are no entries.
Map[K, V].get
pub fn get(self, k: K) yield ?&VThe value for k, if any. (m[k] panics when there is none.)
Map[K, V].getMut
pub fn getMut(inout self, k: K) yield ?inout VThe value for k, to change in place.
Map[K, V].contains
pub fn contains(self, k: K) -> boolWhether there is an entry for k.
Map[K, V].insert
pub fn insert(inout self, k: sink K, v: sink V) -> ?VSets the value for k, returning the old one. A new key goes at the end of
the iteration order; replacing a value keeps the key's place.
Map[K, V].remove
pub fn remove(inout self, k: K) -> ?VRemoves the entry for k, returning its value. The others keep their order.
Map[K, V].entry
pub fn entry(inout self, k: sink K) yield inout V where V: defaultThe value for k, inserting the default first if there is none:
with n = counts.entry(word) { n += 1 }.
Map[K, V].clear
pub fn clear(inout self)Removes every entry.
Map[K, V].keys
pub fn keys(self) -> Vec[K] where K: cloneCopies of the keys, in insertion order.
Map[K, V].values
pub fn values(self) -> Vec[V] where V: cloneCopies of the values, in insertion order.
extend Rc[T]
Rc[T].count
pub fn count(self) -> intHow many rc handles share the value.
Rc[T].downgrade
pub fn downgrade(self) -> Weak[T]A weak handle: it doesn't keep the value alive (for back references that would otherwise make a cycle).
extend Weak[T]
Weak[T].upgrade
pub fn upgrade(self) -> ?Rc[T]A strong handle again, or none when the value is gone.
extend Arc[T]
Arc[T].count
pub fn count(self) -> intHow many arc handles share the value (across threads).
extend Cell[T]
Cell[T].get
pub fn get(self) -> TA copy of the value. A Cell lets copy values inside an rc change.
Cell[T].set
pub fn set(self, v: T)Replaces the value.
extend Mutex[T]
Mutex[T].lock
pub fn lock(self) yield inout TLocking is a projection: the guarded value can't escape the block.
extend Sender[T]
Sender[T].send
pub fn send(self, x: sink T) -> boolSends x (tx <- x): waits while the channel is full, or, unbuffered,
until a receiver takes it. False, and x is dropped, when every
receiver is gone or the task is cancelled.
Sender[T].len
pub fn len(self) -> intThe number of values waiting in the buffer.
extend Receiver[T]
Receiver[T].recv
pub fn recv(self) -> ?TReceives a value (<-rx), waiting for one; none once every sender is
gone and the buffer is empty (or the task is cancelled).
Receiver[T].len
pub fn len(self) -> intThe number of values waiting in the buffer.
extend Task[T]
Task[T].join
pub fn join(sink self) -> TWaits for the task to finish and gives its result.
Task[T].cancel
pub fn cancel(sink self)Cancels the task; the scope still waits for it, and its result is dropped.
extend Iso[T]
Iso[T].take
pub fn take(sink self) -> TThe value, to use in this task.
extend Scope
Scope.cancel
pub fn cancel(self)Cancels the scope: every task in it, and its body.
extend MutexRef[T]
MutexRef[T].lock
pub fn lock(self) yield inout TMutex(&x): locking yields the borrowed place