# Functions

Functions are the main unit of reuse in Vex. A function has a name, typed parameters, an optional return type, and a block body.

Complete programs on this page print their computed values and return `0`
for successful execution. Printed output and process exit status are separate:
returning `42` from `main(): i32` would report a nonzero process status, not
print the number. Fragments without `main` belong inside a program.

## Declaration

The basic form is:

~~~text
fn name(parameter: Type): ReturnType {
    ...
}
~~~

A return type can be omitted for a function that returns unit. Use an explicit return type for public functions and for code where the interface matters.

~~~vex
fn add(left: i32, right: i32): i32 {
    return left + right;
}

fn main(): i32 {
    let answer = add(20, 22);
    $println(answer);
    return 0;
}
~~~

Vex accepts automatic statement boundaries at line breaks. Explicit semicolons are still useful when several statements share a line or when a boundary would be ambiguous.

## Parameters and mutation

Parameters are immutable by default. Use the mutable marker when a function must reassign a parameter:

~~~vex
fn increment(value: i32!): i32 {
    value += 1;
    return value;
}

fn main(): i32 {
    $println(increment(41));
    return 0;
}
~~~

Mutation of a caller-owned value normally requires a mutable binding and a mutable reference. The full rules are covered in [Ownership](../memory/ownership.md) and [Borrowing](../memory/borrowing.md).

~~~text
fn inspect(value: &Point): i32 { ... }
fn update(value: &Point!): i32 { ... }
~~~

Use immutable references for read-only access. A mutable reference is exclusive for the duration of the borrow; the checker rejects conflicting mutable and immutable borrows.

## Return values

Use `return expression` for an explicit return. A final expression without a
terminating semicolon can also supply the function result, for example
`fn double(value: i32): i32 { value * 2 }`. This guide uses explicit returns
when they make control flow clearer. Tuples are the direct way to return more
than one value:

~~~vex
fn divide_with_remainder(left: i32, right: i32): (i32, i32) {
    return (left / right, left % right);
}

fn main(): i32 {
    let (quotient, remainder) = divide_with_remainder(10, 3);
    $println(quotient);
    $println(remainder);
    return 0;
}
~~~

Use an enum such as Result when a function can fail; do not use a magic integer unless the calling contract explicitly requires one.

## Generic functions

Generic functions declare type parameters after the function name:

~~~vex
fn identity<T>(value: T): T {
    return value;
}

fn main(): i32 {
    let value = identity<i32>(42);
    $println(value);
    return 0;
}
~~~

Generic structs use the same angle-bracket syntax. Add a contract bound when the function needs operations beyond those available for every type. See [Generics](../types/generics.md) for type and const parameters, and [Contracts](../types/contracts.md) for constrained APIs.

For a homogeneous variable-length argument list, use a trailing `values: ...T`
parameter. [Typed variadic packs](../types/variadics.md) describe ownership,
borrowed iteration and supported compile-time calls.

## Methods and associated functions

Methods are declared outside the struct with a receiver. The receiver type determines which value owns the method:

~~~vex
struct Point {
    public:
    x: i32,
    y: i32,
}

fn (point: &Point) sum(): i32 {
    return point.x + point.y;
}

fn Point.origin(): Point {
    return Point { x: 0, y: 0 };
}

fn main(): i32 {
    let point = Point.origin();
    $println(point.sum());
    return 0;
}
~~~

The receiver is written as an ordinary parameter inside parentheses. A call such as point.sum() supplies the receiver automatically. Methods can be immutable or mutable; mutable receiver methods require the corresponding mutable reference rules.

## Closures

Closures use pipe delimiters around their parameters:

~~~vex
fn apply(operation: fn(i32): i32, value: i32): i32 {
    return operation(value);
}

fn main(): i32 {
    let double = |value: i32| value * 2;
    $println(apply(double, 21));
    return 0;
}
~~~

A closure can capture values from its surrounding scope. Capture behavior is checked by the ownership and escape analyses, especially when the closure is passed to a go block or stored for later execution.

## Explicit inlining

Use `inline fn` for a small, bounded function whose body must remain visible to
the optimizer at every legal call site:

~~~vex
inline fn isAscii(value: u8): bool {
    return value < 128 as u8;
}
~~~

This is a semantic code-generation contract, not a spelling-based compiler
special case. Vex carries it through HIR and emits the corresponding backend
attribute. It can override ordinary size and loop profitability heuristics,
but it cannot override a semantic prohibition such as a function that the
compiler has proven unsafe to inline.

Prefer ordinary `fn` by default. Use `inline fn` for short dispatchers,
fixed-width primitives, and similar boundaries where caller constants remove
most of the body. Keep large loops in a separate ordinary function and call it
from the inline dispatcher; this preserves specialization without duplicating
the loop at every call site.

## Overloading

Vex supports functions with the same name when their parameter signatures are distinct:

~~~vex
fn measure(value: i32): i32 {
    return value;
}

fn measure(value: f64): f64 {
    return value;
}

fn main(): i32 {
    $println(measure(42));
    return 0;
}
~~~

Resolution considers exact matches, compatible numeric coercions, and generic candidates. Ambiguous calls should be made explicit with an annotation or a type conversion.

## Async functions

Async functions are declared with async fn. Await is valid inside an async function or async execution context:

~~~vex
async fn get_value(): i32 {
    return 42;
}

async fn main(): i32 {
    let value = await get_value();
    $println(value);
    return 0;
}
~~~

`await` suspends the current async computation until its result is available.
Keep borrowed data valid across that suspension and use the owning API's
cancellation and cleanup rules. See [Async](../concurrency/async.md) for task
execution and synchronization. An ordinary synchronous function cannot use
`await`.

## Choosing a callable shape

- Use a named function for reusable behavior without a captured environment.
- Use a method when the operation belongs to a receiver; declare it with
  `fn (self: &Type)` or `fn (self: &Type!)` rather than an `impl` block.
- Use a closure when the operation needs values from its surrounding scope.
- Use `fn(Args): R` for a callback parameter and `async fn` for a computation
  that can suspend.
- Use a [typed variadic pack](../types/variadics.md) for a varying number of
  arguments of one element type; use a `Span<T>` to borrow an existing sequence.

## Next steps

- [Control Flow](control-flow.md)
- [Structs](../types/structs.md)
- [Generics](../types/generics.md)
- [Contracts](../types/contracts.md)
- [Closures](../types/closures.md)
- [Async](../concurrency/async.md)
