Skip to content

Functions

Bodies, parameters, defaults, mutable parameters, return types, fallible signatures, effect rows, generics, methods, and function values.

fn declares a callable unit. The same keyword introduces free functions, methods, static functions, trait requirements, and stdlib signatures. Function and parameter names use snake_case.

fn add(a int, b int) int {
    return a + b
}

fn main() void {
    println("${add(20, 22)}")
}

Bodies

A block body holds statements, early returns, and an optional final tail expression. The tail expression is the result — no return keyword needed.

fn absolute(value int) int {
    if value < 0 {
        return -value
    }
    value
}

fn category(value int) string {
    if value < 0 {
        return "negative"
    }
    if value == 0 {
        return "zero"
    }
    "positive"
}

fn main() void {
    println("${absolute(-7)} ${category(0)} ${category(3)}")
}

When the whole body is one expression, use => instead of braces.

fn double(value int) int => value * 2

fn is_even(value int) bool => value % 2 == 0

fn describe(value int) string => "${value} is even: ${is_even(value)}"

fn main() void {
    println(describe(double(21)))
}

An => body is checked against the declared return type exactly like a block’s tail expression. It may be any expression, including an if or a match:

enum Level { Low, High }

fn threshold(l Level) int => match l {
    Low => 10
    High => 90
}

fn clamp_high(value int) int => if value > 90 { 90 } else { value }

fn main() void {
    println("${threshold(High)} ${clamp_high(120)}")
}

Give every normally completing path a value. A path that returns, propagates an error, or otherwise diverges does not need to produce the block’s tail value, so an early-return branch never forces the remaining branch to manufacture a placeholder.

Parameters

Parameters are name-and-type pairs, the type right after the name, and calls supply them positionally. value: int is the old spelling: it is read the same and warned (ATOLL1120), with the fix atoll fix writes.

fn clamp(value int, minimum int, maximum int) int {
    if value < minimum { return minimum }
    if value > maximum { return maximum }
    return value
}

fn main() void {
    println("${clamp(150, 0, 100)} ${clamp(-5, 0, 100)} ${clamp(42, 0, 100)}")
}

Argument count is checked exactly:

fn add(a int, b int) int => a + b

fn main() void {
    println("${add(1)}")
}

Named call arguments and variadic parameters are not part of the language. When an argument list grows past what a reader can keep straight, take a struct instead of adding more positional parameters.

struct ConnectOptions {
    host       string
    port       int
    secure     bool
    timeout_ms int
}

fn connect(options ConnectOptions) string {
    scheme := if options.secure { "https" } else { "http" }
    return "${scheme}://${options.host}:${options.port} (${options.timeout_ms}ms)"
}

fn main() void {
    println(
        connect(
            ConnectOptions {
                host:       "db.internal"
                port:       6432
                secure:     false
                timeout_ms: 250
            }
        )
    )
}

Defaults

A parameter may carry a default value. Defaults fill an omitted trailing suffix, left to right.

const DEFAULT_PORT: int = 5432

fn connect(host string, port int = DEFAULT_PORT, secure bool = true) string {
    scheme := if secure { "https" } else { "http" }
    return "${scheme}://${host}:${port}"
}

fn main() void {
    println(connect("db.internal"))
    println(connect("db.internal", 6432))
    println(connect("db.internal", 6432, false))
}

Because calls are positional, a caller cannot skip port and supply only secure. Once a parameter has a default, every parameter after it must have one too:

fn f(a int = 1, b int) int => a + b

fn main() void {
    println("${f(1, 2)}")
}

Default expressions fold at compile time. They may use literals and constants, but they cannot read the caller’s runtime state.

A default is checked against the parameter’s type at the declaration, as an argument is at a call. A union parameter takes a default of one of its members:

fn label(id int | string = 7) int {
    return match id {
        int(n) => n
        string(s) => s.len()
    }
}

fn main() int {
    return label()
}

An optional parameter takes a default of what it holds, as a binding’s initializer does, and an omitted argument is that value present:

fn retries(limit int? = 5) int {
    return limit ?? 0
}

fn main() int {
    return retries() + retries(40)
}

It also takes None, and an omitted argument is then absent:

fn label_len(label string? = None) int {
    return match label {
        Some(s) => s.len()
        None => 7
    }
}

fn main() int {
    return label_len() + label_len("hello")
}

A parameter of a struct or enum type defaults to a constant of that type, declared anywhere at the top of the file. The argument is the constant itself, as a use of its name is, and a struct field’s default works the same way:

struct RecordType {
    number int
}

const ADDRESS: RecordType = RecordType { number: 1 }

fn lookup(name string, kind RecordType = ADDRESS) int {
    return name.len() * 100 + kind.number
}

fn main() int {
    return lookup("a") + lookup("", RecordType { number: 28 })
}

A value built of aggregates written in place as a default is ATOLL1019. Name it as a constant, and write the constant as the default.

The three rungs

A parameter says what the callee may do with what it is handed: keep it (x T), read it (x &T), write the caller’s value (x &mut T), or take a block it may write and keep (mut p ^T). The whole table, with the call that goes with each, is on Pointers; this page shows the shapes in use.

You write The callee The caller
x T owns it — may keep it in a field, a collection, a closure hands it over
x &T borrows it — may read, may not keep keeps the release
x &mut T writes the caller’s T, and never keeps it passes &mut place; the place must be mut
&mut self aliases the receiver sees the write

mut x T makes the parameter a binding of the callee’s own, which the body may write and reseat; it never writes the caller’s value, which is the &mut row.

The borrow goes on the type; mut goes on the binding, left of the name. A borrow is a statement about the type a caller must supply, and a mode is a statement about the binding, so each is written where its subject is. &p: T — the marker before the name — is ATOLL1072.

A borrow is a type, so a return type, a local’s annotation and a type argument may be one as well; it may not outlive what it borrows, and a reference that owns its block is ^T.

struct Point { x int, y int }

fn look(p &Point) int { return p.x }      // borrows

fn main() int {
    n: Point = Point { x: 7, y: 0 }
    return look(n)
}

Owning is the default because it is the permissive one: a callee that stores its argument somewhere needs no ceremony, and a callee that promises not to says so with one character.

mut on a binding is a writable place in this frame. It does not write the caller’s argument slot. A borrow and a binding mode do not compose (ATOLL1053): write p &mut T to write the caller’s value, not mut p &T:

fn f(mut x &int) int { return x }

fn main() int {
    mut n: int = 7
    return f(n)
}

A name is given once in a parameter list, self included; a second is refused beside the first (ATOLL3013). _ may be given any number of times, and binds nothing, so return _ names nothing (ATOLL1009).

struct G { id int }

fn twice(x G, x G) int { return x.id }    // refused: `x` is given twice

fn main() int {
    return twice(G { id: 1 }, G { id: 2 })
}

front-fail=ATOLL3013 marks a refusal the new compiler gives. Today’s compiler reads the last x, and answers 2.

Mutable parameters

Prefix a binding with mut when the body assigns to it, a parameter taken by value among them. Such a parameter is the callee’s own, as a mut local is, whatever its type: twice(a) writes its own n, and the caller’s a is untouched. Writing the caller’s value is p &mut T and &mut place at the call. A parameter written to without mut is refused, with help to declare it mut n int or take it n &mut int. A function with no body has no frame for the binding, so mut on its parameters is refused. &mut self is separate: xs.push(4) requires mut xs.

fn twice(mut n int) int {
    n = n * 2
    return n
}

fn main() int {
    a: int = 21
    b: int = twice(a)
    return a * 1000 + b      // 21 and 42 — the caller's `a` is untouched
}

front-run=21042 marks an answer the new compiler gives. Today’s compiler refuses mut n int (ATOLL1063); there scratch is a local:

fn twice(n int) int {
    mut scratch: int = n
    scratch = scratch * 2
    return scratch
}

fn main() int {
    a: int = 21
    b: int = twice(a)
    return a * 1000 + b      // 21 and 42 — the caller's `a` is untouched
}
fn main() int {
    mut xs: List[int] = [1, 2, 3]
    xs.push(4)
    return xs.len()
}

The argument has to be a mutable place — a mut binding, or a field or index of one. An immutable binding or a literal cannot satisfy the contract:

fn push(xs &mut List[int]) void { xs.push(4) }

fn main() int {
    xs: List[int] = [1, 2, 3]
    push(&mut xs)
    return xs.len()
}

A receiver is spelled as a parameter is

A receiver is a parameter named self, and it takes the markers every parameter takes: self owns what it is handed, &self borrows it, and &mut self borrows it and writes the caller’s value.

spelling the method
&self reads the receiver; the caller keeps it
&mut self writes the caller’s value in place
self takes the receiver: a value nothing reads afterwards moves in, one that is read afterwards is shared
struct Counter {
    v int

    fn get(&self) int { return self.v }
    fn bump(&mut self) void { self.v = self.v + 1 }
    fn take(self) int { return self.v }
}

fn main() int {
    mut c: Counter = Counter { v: 7 }
    c.bump()
    return c.get() + 0 * c.take()
}

mut self takes the receiver as self does, and the body may write it: as mut on any parameter taken by value, it is a binding of the method’s own, never the caller’s value.

struct Counter {
    v int

    fn bumped(mut self) int {
        self.v = self.v + 1
        return self.v
    }
}

fn main() int {
    c := Counter { v: 7 }
    return c.bumped()       // 8, and `c` is handed over
}

planned marks a design not built yet. Today’s compiler refuses mut self (ATOLL1048), and the new compiler takes it once its parser does.

@owned self is refused (ATOLL1048); it was the spelling of a different default.

struct Counter {
    v int

    fn take(@owned self) int { return self.v }
}

fn main() int {
    c: Counter = Counter { v: 7 }
    return c.take()
}

A parameter written T owns its argument, as a binding does, and a parameter written &T reads it and leaves it with the caller. See Values.

Return types

Write the type right after the parameter list: fn answer() int. void is the spelling for “no useful result”; Unit is accepted as a synonym, and the annotation may be omitted entirely. A record type and the never type take a : first, fn metrics(): { count: int } and fn spin(): !, because bare they would read as the body and as the error marker; anywhere else : T and -> T are the old spellings, warned as ATOLL1120.

fn answer() int {
    return 42
}

fn log_ready() void {
    println("ready")
}

fn log_done() Unit {
    println("done")
}

fn total(xs []int) {
    mut sum := 0
    for x in xs {
        sum += x
    }
    return sum
}

fn main() void {
    log_ready()
    log_done()
    println("${answer()} ${total([1, 2, 3])}")
}

total has no annotation, so the checker infers int from its return. That is convenient inside a file and risky across one: an edit to the body silently changes the API. State the type on anything other code depends on.

Record results

A function can return an anonymous record when the caller only needs a few fields together and a named struct would be ceremony. The type is structural: any record with the same field names and types is the same type, so a second declaration can accept the result without either one naming a struct.

fn metrics(xs []int): { count: int, total: int, empty: bool } {
    mut total := 0
    for x in xs {
        total += x
    }
    return { count: xs.len(), total: total, empty: xs.is_empty() }
}

fn describe(m { count: int, total: int, empty: bool }) string {
    if m.empty {
        return "no samples"
    }
    return "${m.count} samples, total ${m.total}"
}

fn main() void {
    println(describe(metrics([3, 4, 5])))
    println(describe(metrics([])))

    m := metrics([1, 2])
    println("${m.count} ${m.total} ${m.empty}")
}

Repeat the field list once too often and a named struct has become the better trade — the record form is for a result that only one or two call sites ever destructure.

The ::result projection

fnname::result names a declaration’s success type, so a helper can follow a signature without restating it.

fn version_code() int => 140

fn is_supported(v version_code::result) bool => v >= 100

fn main() int {
    if is_supported(version_code()) { return 1 }
    return 0
}

The projected type can be anything the function returns — a scalar, a struct, a list, an anonymous record. Its sibling fnname::err, covered under fallible functions, projects the error channel the same way.

Fallible functions

A function that can fail declares T ! E: T on success, E in the error channel.

error ParseError { Empty, NotANumber }

fn parse_port(text string) int ! ParseError {
    if text.len() == 0 {
        error Empty
    }
    match text.to_int().ok() {
        Some(v) => return v
        None => error NotANumber
    }
}

fn open(text string) string ! ParseError {
    port := parse_port(text)?
    return "listening on ${port}"
}

fn main() void {
    println(open("8080").unwrap_or("bad port"))
    println(open("nope").unwrap_or("bad port"))
}

Inside the body, return and the tail expression produce the success type, and error Variant exits through the error channel. At a call site the value is a Result[T, E]: ? propagates it, catch converts it, and unwrap_or supplies a fallback.

The error type of a declaration can be named without repeating it, using the ::err projection — ::result does the same for the success type:

error LoadError { Missing, Corrupt }

fn load(id int) string ! LoadError {
    if id < 0 {
        error Missing
    }
    return "record ${id}"
}

fn explain(e load::err) string {
    match e {
        Missing => return "not found"
        Corrupt => return "damaged"
        _ => return "unknown"
    }
}

fn main() void {
    text := load(-1) catch {
        err => {
            println(explain(err))
            return
        }
    }
    println(text)
}

The catch arm above returns, so text is a plain string. An arm that produces a value instead rewrites the error channel and leaves another Result — see Catch.

Note the binding name: error is a keyword, so an arm cannot bind error — use err or e. Full detail lives in Errors.

Effect rows

A signature may declare the effects its body performs, in square brackets after using. The five effects are Suspend, Error, Alloc, Spawn, and Cancel.

error TaskError { Cancelled }

fn allocating() []int {
    return [1, 2, 3]
}

fn failing(v int) int ! TaskError {
    if v < 0 {
        error Cancelled
    }
    return v
}

fn concurrent() int {
    left := spawn { 20 }
    right := spawn { 22 }
    return left.await().unwrap_or(0) + right.await().unwrap_or(0)
}

fn main() void {
    println("${allocating().len()} ${concurrent()} ${failing(1).unwrap_or(0)}")
}

A row is a contract for readers and for API review. When it is omitted the compiler infers the union transitively through the call graph, and a row that under-states what the body reaches produces a warning rather than blocking the build — so write the row on exported functions, where the diagnostic is the point.

Generics

Type parameters go in square brackets after the name. Bounds are written inline or in a where clause; the two forms mean the same thing.

fn identity[T](value T) T => value

fn larger[T: Comparable[T]](a T, b T) T {
    if a > b { return a }
    return b
}

fn best[T](xs &[]T) &T? where T: Comparable[T] {
    return xs.max()
}

fn pair_up[T, U](a T, b U) (T, U) => (a, b)

fn main() void {
    println("${identity(7)} ${larger(2, 9)} ${best([3, 9, 4]) ?? 0}")
    println("${identity("text")} ${larger("alpha", "beta")}")

    p := pair_up(1, "one")
    println("${p.0}=${p.1}")
}

Every call selects its own substitution: a call with int does not specialize the declaration for a later call with string.

A bound is a promise the argument type has to keep, so a generic function is only as usable as the implementations that exist. Display is instructive: the stdlib provides it for string, bool and the numbers, and a type gains it by writing the impl. A type with only an inherent to_string still renders in "${x}", but a T: Display bound does not accept it.

struct Tag { name string }

impl Display for Tag {
    fn write_to(&self, out &mut string) void {
        out.append("#")
        out.append(self.name)
    }
}

fn labelled[T](value T) string where T: Display => "value=${value.to_string()}"

fn main() void {
    println(labelled(Tag { name: "release" }))
    println(labelled("plain"))
    println(labelled(true))
}

See Generics.

Methods

A function whose first parameter is self or &mut self is a method. It can be declared directly in the type body.

struct Counter {
    value int
    step  int

    fn current(&self) int => self.value

    fn increment(&mut self) void {
        self.value += self.step
    }

    fn advanced(&self, times int) Counter =>
    Counter { value: self.value + self.step * times, step: self.step }
}

fn main() void {
    mut c := Counter { value: 0, step: 5 }
    c.increment()
    c.increment()
    println("${c.current()} ${c.advanced(3).value}")
}
Receiver Capability
no self static function, called through the type
self read fields and call non-mutating behaviour
&mut self assign through the receiver

A function inside a type body without self is static:

struct Point {
    x float
    y float

    fn zero() Point => Point { x: 0.0, y: 0.0 }
    fn unit_x() Point => Point { x: 1.0, y: 0.0 }
}

fn main() void {
    o := Point.zero()
    println("${o.x} ${Point.unit_x().x}")
}

The same methods can come from an impl block:

struct Vec2 { x float, y float }

impl Vec2 {
    fn zero() Vec2 => Vec2 { x: 0.0, y: 0.0 }
    fn length(&self) float => (self.x * self.x + self.y * self.y).sqrt()
    fn scaled(&self, k float) Vec2 => Vec2 { x: self.x * k, y: self.y * k }
}

fn main() void {
    v := Vec2 { x: 3.0, y: 4.0 }
    println("${v.length()} ${v.scaled(2.0).y} ${Vec2.zero().x}")
}

In a method, Self written as a type is the method’s owner, so scaled may answer Self for Vec2. In a free function Self names nothing (ATOLL1009).

struct Vec2 { x float, y float }

impl Vec2 {
    fn scaled(&self, k float) Self => Vec2 { x: self.x * k, y: self.y * k }
}

fn main() void {
    println("${Vec2 { x: 1.0, y: 1.0 }.scaled(2.0).x}")
}

planned marks a design not built yet. Today’s compiler reads Self there as a type of its own and refuses the program (ATOLL2002), so the examples above write the concrete type name.

Receiver-prefix functions

A method can also be declared at the top level by prefixing the receiver type to the name. This attaches behaviour from the module that needs it, without reopening the type declaration.

struct Reading { celsius float }

fn Reading.fahrenheit(&self) float => self.celsius * 1.8 + 32.0

fn Reading.warmer(&self, by float) Reading => Reading { celsius: self.celsius + by }

fn Reading.reset(&mut self) void {
    self.celsius = 0.0
}

fn main() void {
    mut r := Reading { celsius: 20.0 }
    println("${r.fahrenheit()} ${r.warmer(5.0).celsius}")
    r.reset()
    println("${r.celsius}")
}

Leave the self off and the same form declares a static — reached as Type.name(), exactly like one declared anywhere else:

struct Reading { celsius float }

fn Reading.freezing() Reading => Reading { celsius: 0.0 }

fn main() void {
    println("${Reading.freezing().celsius}")
}

A static is not callable on an instance: r.freezing() names no method on Reading.

The type body and an impl block are the other two places to put one, and the call site is identical from all three:

struct Reading { celsius float }

impl Reading {
    fn freezing() Reading => Reading { celsius: 0.0 }
    fn boiling() Reading => Reading { celsius: 100.0 }
}

fn Reading.fahrenheit(&self) float => self.celsius * 1.8 + 32.0

fn main() void {
    println("${Reading.freezing().fahrenheit()} ${Reading.boiling().fahrenheit()}")
}

Call syntax is value.method() or Type.function() regardless of which of the three declaration sites was used. Trait implementations are covered in Implementations.

Function values

fn(A, B) -> R is the type of a function value. Named functions and closures both inhabit it.

fn double(value int) int => value * 2

fn apply(value int, operation fn(int) -> int) int {
    return operation(value)
}

fn main() int {
    return apply(21, double)
}

A closure inhabits the same type, with or without written parameter types:

fn apply(value int, operation fn(int) -> int) int {
    return operation(value)
}

fn main() int {
    return apply(21, (v int) => v * 2)
}

Function values are ordinary values: they go in struct fields, get returned, and get selected at run time.

struct Handler { run fn(int) -> int }

fn double(value int) int => value * 2

fn main() int {
    h: Handler = Handler { run: double }
    return h.run(21)
}
fn pick() fn(int) -> int {
    return (v int) => v * 2
}

fn main() int {
    f := pick()
    return f(21)
}

A method named by its type is a function value too, as Rust’s Point::norm is: the receiver is its first parameter, &Point where the method takes &self, &mut Point where it takes &mut self. A static method is the function it declares.

struct Point { x int }

impl Point {
    fn at(x int) Point => Point { x: x }
    fn twice(&self) int => self.x * 2
}

fn main() int {
    points: []Point = [1, 20].map(Point.at).collect()
    doubled: []int = points.map(Point.twice).collect()
    return doubled[0] + doubled[1]
}

A []fn(int) -> int lowers, and so does a struct field holding a closure with the struct inside a collection — see Closures.

A function type may also be fallible. Compatibility covers parameter types, the success type, and the error type — a closure is never erased into an untyped callback. A value of fallible function type has the Result spelled out, because that is what a call to it produces:

error MathError { DivideByZero }

fn checked_div(a int, b int) int ! MathError {
    if b == 0 {
        error DivideByZero
    }
    return a / b
}

fn checked_mod(a int, b int) int ! MathError {
    if b == 0 {
        error DivideByZero
    }
    return a % b
}

fn run(op fn(int, int) -> Result[int, MathError], a int, b int) string {
    value := op(a, b) catch {
        err => return "error"
    }
    return "${value}"
}

fn main() void {
    println(run(checked_div, 10, 2))
    println(run(checked_mod, 10, 3))
    println(run(checked_div, 10, 0))
}

The T ! E spelling belongs to a declaration’s return type; Result[T, E] is the type of the value that declaration hands back, and so is what a fn(...) -> ... type needs.

Closures are documented in Closures; call mechanics in Calls.

A complete example

Defaults, methods, receiver-prefix functions, a fallible signature, and a function parameter in one file:

const DEFAULT_WIDTH: int = 24

error ReportError { NoSamples, Negative }

struct Series {
    label  string
    points []float

    fn total(&self) float {
        mut sum := 0.0
        for p in self.points {
            sum += p
        }
        return sum
    }

    fn mean(&self) float ! ReportError {
        if self.points.is_empty() {
            error NoSamples
        }
        return self.total() / self.points.len().to_float()
    }
}

fn Series.peak(&self) float? => self.points.max()

fn bar(fraction float, width int = DEFAULT_WIDTH) string {
    mut filled := (fraction * width.to_float()).to_int()
    if filled < 0 { filled = 0 }
    if filled > width { filled = width }

    mut out := ""
    for i in 0..width {
        if i < filled { out += "#" } else { out += "." }
    }
    return out
}

fn render(s &Series, scale fn(float) -> float) string ! ReportError {
    avg := s.mean()?
    if avg < 0.0 {
        error Negative
    }
    top := s.peak() ?? 1.0
    return "${s.label} ${bar(scale(avg) / top)} avg=${avg}"
}

fn main() void {
    series := [
        Series { label: "cpu", points: [0.2, 0.6, 0.4] },
        Series { label: "mem", points: [] }
    ]

    for s in series {
        line := render(s, v => v) catch {
            err => {
                println("${s.label} (no data)")
                continue
            }
        }
        println(line)
    }
}

API boundaries

Bodies can stay expression-oriented and heavily inferred. Exported signatures should do the opposite — the following are all compatibility surface, and a caller can break on any of them:

  • parameter order, types, and mut;
  • the success type and the error type;
  • parameter defaults, because existing calls keep compiling and change behaviour;
  • generic parameters and their bounds;
  • the declared effect row.

When several optional settings start evolving together, replace the trailing default suffix with an options struct: adding a field is then an additive change instead of a new positional parameter.

Known gaps

The blocks above marked run= are compiled and executed by the compiler’s own test suite. for … in, ??, field and element +=, defer, ?, and catch all reach code generation. ErrorUnionCoerce has no producer — both directions across a union are built without that node.

Nothing on this page is known not to build.

Type to search…

↑↓ navigate↵ selectEsc close