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 provide a way to encapsulate frequently used code into sub-routines. These sub-routines can then be called to execute their code with a specific set of parameters.

The function definition starts with the keyword fn, followed by an identifier, a parameter list, and a function body.

test

// define function print_error with text as parameter of type String
fn print_error( text: String ) {
    // code body
    std::print("ERROR: {text}");
}

print_error("first");
print_error("second");
Output
ERROR: first
ERROR: second

Default Parameters

Parameters can include default values. Default values are specified without an explicit type annotation, but their type is inferred from the unit of the provided value.

test

fn f(x: Scalar, y=1mm) -> Length {
    x * y
}

std::debug::assert_eq([ f(2), 2mm ]);
std::debug::assert_eq([ f(2, 2mm), 4mm ]);

Functions may be declared within source files, modules or workbenches.