Functions
Typed parameters, multiple results, variadic calls, and predictable value semantics.
Declare a function#
An ordinary function parameter is written as a name followed by its type, such as left int. The result type follows the parameter list. Functions can call declarations that appear later, and recursion is supported. Executables use func main() or func main() int.
A function declaration separates the operations it performs from the places that call it. The parameter list gives each input a name and a type. Those names are local to the function body. A result type tells callers what value to expect; omitting it declares a function with no result.
return ends the current call. In a value-returning function, provide an expression compatible with the result type. An ordinary return may omit its trailing semicolon when the next token is }, including the brace closing an if, loop, or switch block. For example, func answer() int { return 42 } is valid. This also applies to a bare return or multiple returned values. A newline alone does not replace the semicolon; keep it when another statement follows. The return panic form still requires a semicolon. Functions declared in any source file of the same package can call one another without a separate forward declaration.
func add(left int, right int) int {
return left + right;
}
func main() int {
return add(2, 3);
}
The call add(2, 3) binds left to 2 and right to 3, then returns 5. Here main returns that number as the process exit status. For a program that simply prints output and succeeds, use func main() without a result type.
Multiple results#
List result types in parentheses and unpack a call into multiple bindings. Use _ to discard an individual result. If a function call produces several results, it can appear by itself after return to return all those results. It can also be the only argument expression in another call, supplying that call’s entire argument list in order.
Multiple results are useful when an operation has both a value and a status. Callers can handle them together without defining a one-off wrapper struct. The number and types of expressions in a return must agree with the declared result list.
In the example, division by zero is an expected failure represented by false. The caller should check that flag before using the result as a successful quotient. When a result is deliberately unnecessary, use _ for that position rather than introducing an unused descriptive name.
func divide(a int, b int) (int, bool) {
if (b == 0) return 0, false;
return a / b, true;
}
// Inside a function:
value, ok := divide(12, 3);
After divide(12, 3), value is 4 and ok is true. Calling divide(12, 0) instead gives 0 and false. You can write value, _ := divide(12, 3); when a surrounding condition already guarantees a valid divisor.
Variadic parameters#
A final ...T parameter accepts zero or more values. Use a final array... argument to expand an existing array. The called function receives an array containing independent copies of the supplied values. ...any accepts a mixture of concrete types.
A variadic parameter gathers its arguments into an array that can be indexed or traversed. The element type after ... constrains each supplied item. A variadic parameter must be last, after any required fixed parameters. A call with no variadic items provides an empty collection.
Expansion is written on the final argument expression, not on each element. It can follow explicit variadic items, so total(10, numbers...) includes ten before the array contents. Raw buffers cannot be expanded because they do not carry the required array length.
func total(values ...int) int {
result := 0;
for (i, value := range values) {
result += value;
}
return result;
}
// Inside a function:
numbers := int[]{2, 4, 6};
answer := total(numbers...);
The call shown returns 12. Inside total, each range iteration adds an element copy to result. Passing numbers... does not make the function share mutable ownership of the caller’s collection; the value-copy rules still apply.
Function literals and closures#
Function literals use func(parameters) resultType { body }; omit the result type for a function with no results. Their types use the same signature without the body: func(int) int, func(), or func() (int, bool). When assigning a function value to a function-typed variable or passing it to a function-typed parameter, the source function and destination function type must agree on each parameter type, each result type, and whether the final parameter is variadic. This includes numeric storage widths: func(i32) int and func(int) int are different types. Parameter names are not part of that comparison. Functions can be assigned to variables, passed as arguments, returned, stored in structs or arrays, and boxed in any. A named function can also be passed or assigned as a value. For a generic function, choose its concrete type arguments first: identity<int> selects the integer version of identity. Function literals can use outer generic type parameters but cannot declare their own type parameters.
Closures capture variables by reference. The surrounding function and sibling closures share updates to a captured variable. Returning a closure preserves its captures; copying a function value shares the same environment. Separate calls to a factory create independent environments. Each iteration gets separate storage for range bindings and variables declared inside the loop body. A variable declared once in the loop initializer is instead shared across iterations, so closures capturing that variable see updates to the same storage. Captured storage currently lives until process exit, when the runtime releases its owned values. Raw pointer and buffer captures still borrow their pointees and backing storage.
Use a type alias for arrays of functions, such as type Callback = func() int; then callbacks: Callback[3];. In func() int[3], the [3] is part of the function’s result type: it describes a function returning a three-element integer array. To declare a three-element array of functions, use the Callback alias followed by [3]. An uninitialized function value panics if called. Function values use an Ocean closure ABI and cannot be passed directly as native C function pointers. Calls through interface methods dispatch to the boxed concrete receiver. Interface values, including any, default to null and accept null assignment, arguments, and returns. Check iface == null or iface != null. Calling a method on a null interface panics and supports ordinary defer and recover. Bound method values remain unsupported.
func map(data array<int>, closure func(int) int) int[] {
result := make(int[]);
for (i := 0; i < len(data); i++) {
result.append(closure(data[i]));
}
return result;
}
func main() int {
offset := 3;
values := int[2]{1, 2};
mapped := map(values, func(n int) int { return n + offset; });
return mapped[0] + mapped[1]; // 9
}
The function literal reads offset from its surrounding scope. Here map calls the function with 1 and 2, so the returned array contains 4 and 5, and main returns 9. A later change to a captured variable would be visible to the closure because the capture refers to the variable’s storage.