-
Notifications
You must be signed in to change notification settings - Fork 0
Description
Functions
Functions can be made public with the pub keyword.
Keep in mind that function names should follow camelCase conventions; if they don't, a warning will be emitted.
Parameters
Function arguments are limited to u16::MAX_SIZE.
Default values
You can provide default values for parameters using the = syntax with a compile-time expression:
func open(path: string, mode: string = "r", timeout: i32 = 30) { /* … */ }
When a parameter with a default value is omitted at the call site, the default expression is used instead. Defaults must be constant evaluable expressions.
Note
Defaults may reference earlier parameters by name only if those names are constants in scope. Variadic
parameters cannot have defaults.
Variadic parameters
A variadic parameter, declared with ...name: Type, must appear as the final parameter. It collects zero or more additional arguments of the specified type:
func log(tag: string, ...parts: string) { /* … */ }
log("INFO") // parts = []
log("INFO", "a", "b") // parts = ["a", "b"]
Inside the function body, a variadic parameter is treated as an array of the specified type.
Calling functions
Positional arguments
The simplest way to call a function is by passing arguments in the order they're declared:
func join(a: string, b: string = ",") -> string { /* … */ }
join("x", "y") // a = "x", b = "y"
join("x") // a = "x", b = "," (default)
Named arguments
You can also specify arguments by parameter name, which allows for more flexibility:
func open(path: string, mode: string = "r", timeout: i32 = 30) { /* … */ }
open("/tmp/x") // mode = "r", timeout = 30
open(path = "/tmp/x", timeout = 5) // mode = "r" (default)
open("/tmp/x", timeout = 5) // positional then named – OK
open(timeout = 5, path = "/tmp/x") // all named – OK, order is free
When mixing positional and named arguments, keep these rules in mind:
- Positional arguments must come first
- Once you use a named argument, all subsequent arguments must be named
- Each parameter can be supplied at most once (either by position or by name)
- Named arguments can be given in any order after the positional prefix
Note
Named arguments don't apply to individual elements captured by a variadic parameter. The variadic parameter itself cannot be passed by name. Supply its elements positionally after all fixed parameters.