Functions (v0.2.1)

Function declarations, arguments, return types, and visibility.

Latest

Overview

Functions declare their parameters and return type in the signature. If no return type is written, the function returns void.

Attributes can be placed after the signature to export the function, bind it to an external symbol, or set a calling convention.

Write small functions with clear inputs and clear return behavior. This is especially important when a function owns memory or reports errors through status codes.

Primary source: syntax/function/function.md

Syntax Signatures

fn sum(a: s32, b: s32) s32 @public {
    return a + b;
}

fn main() s32 @public {
    return sum(2, 3);
}

Behavior and Use

Use the return type to make the result clear. If a function can fail, choose a status code, nullable pointer, or another convention and use it consistently.

Put calling and linking attributes on functions that connect to outside code. Keep internal helpers simple.

Best Practices

Signature Parts

A function signature states the name, parameters, return type, and optional attributes.

Return and Ownership Conventions

The signature should make error and ownership behavior predictable.

Example

fn clamp(x: s32, low: s32, high: s32) s32 @public {
    if x < low {
        return low;
    }
    if x > high {
        return high;
    }
    return x;
}

Back to language reference