Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Functions

Functions are declared with the fn keyword.

Basic Functions

fn greet() {
    print("Hello, World!")
}

greet()

Parameters

Functions can accept parameters:

fn greet(name) {
    print("Hello, " + name + "!")
}

greet("Alice")

Return Values

Functions return the last expression:

fn add(x, y) {
    x + y
}

let result = add(5, 3)  // 8

Explicit return:

fn max(x, y) {
    if x > y {
        return x
    }
    return y
}

Type Annotations

Specify parameter and return types:

fn add(x: int, y: int) -> int {
    x + y
}

First-Class Functions

Functions are first-class values:

fn apply(f, x) {
    f(x)
}

fn double(x) {
    x * 2
}

let result = apply(double, 5)  // 10

Closures

(Coming soon: Closures that capture variables from their environment)

Next Steps