Functions (v0.2.1)
Function declarations, arguments, return types, and visibility.
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
- Keep function bodies small and move complexity into helpers.
- Document important input rules near the function declaration.
- Keep exported functions focused on one job.
Signature Parts
A function signature states the name, parameters, return type, and optional attributes.
- Parameters are written as name: Type and are checked at call sites.
- The return type follows the parameter list. If omitted, the function returns void.
- @public exports the function. @extern and @convention describe how the function connects to external symbols.
- Named arguments can make call sites clearer when several parameters have the same type.
Return and Ownership Conventions
The signature should make error and ownership behavior predictable.
- Use status-code returns when a function can fail but does not produce a value.
- Use nullptr or another documented sentinel when returning a pointer that may be absent.
- If a function returns owned memory, document which function releases it and keep that convention consistent.
Example
fn clamp(x: s32, low: s32, high: s32) s32 @public {
if x < low {
return low;
}
if x > high {
return high;
}
return x;
}