Skip to content

Overview of RETURN Statements

RETURN ends a function call and optionally supplies its result. The RETURN expression; form supplies the result of a value-returning function. The RETURN; form leaves a VOID function early.

Returning values

::minimum FUNCTION(@left I32, @right I32): I32
{
  IF (left < right)
  {
    RETURN left;
  }
  RETURN right;
}

The returned expression must be usable to construct the declared return type. Normal conversion and constructor rules apply.

Omitting the return type makes a function VOID:

::write_positive FUNCTION(@value I32, @destination WRITE& I32)
{
  IF (value <= 0)
  {
    RETURN;
  }
  destination := value;
}

Deduced and reference results

AUTO lets a function instantiation deduce its result type from a return expression:

::twice FUNCTION(@value AUTO): AUTO
{
  RETURN value + value;
}

A reference return names existing storage rather than copying the object:

::box STRUCT
{
  .value VAR I32;

  .get FUNCTION(): MUT& I32
  {
    RETURN .value;
  }
}

The returned reference becomes invalid when the referenced object's lifetime ends. Retaining it without using it is permitted. Using it, including copying it, creating another reference from it, or taking its address after invalidation, is undefined behavior. A forwarding function uses FORWARD with a reference-preserving return type:

::identity FUNCTION(@ARG:value AUTO& AUTO): DECLTYPE(value)
{
  RETURN FORWARD(value);
}

Lexicographic comparisons

RETURN_UNEQUAL compares two expressions with <=> and returns the result only when they differ. This keeps multi-field comparators concise:

::compare_pair FUNCTION(@left_a I32, @right_a I32,
                        @left_b I32, @right_b I32): ORDER
{
  RETURN_UNEQUAL left_a, right_a;
  RETURN_UNEQUAL left_b, right_b;
  RETURN ORDER::EQUAL;
}

Reference

See the RETURN Statements Reference for result construction, deduced returns, reference lifetime requirements, fallthrough, and the exact RETURN_UNEQUAL behavior.