#Functions
Status: language specification draft.
This chapter defines functions, hd-lang's primary unit of behavior.
- fn.kind.ordinaryMethods, entry points, tests, tools, workflows, and generated adapters are ordinary functions with additional library metadata or calling conventions.
fn square(n: i32) -> i32: n * n
fn demo() -> i32:
square(3) + square(4) # 25#Declarations
A named function declares typed parameters and a result type.
fn add(a: i32, b: i32) -> i32:
a + b
fn load_user!(id: UserId) -> Result[User, DbError] $ Database:
...- fn.decl.suspendingA name ending in
!declares a suspending function. - fn.decl.requirementsA trailing
$clause declares requirements. - fn.limit.complexityAn implementation may limit the work of checking one item, such as a function body. The limit is implementation-defined.
- fn.limit.complexity.errorAn item whose check exceeds that limit is an error, reported on the item. Error:
item-too-complex.
#Parameter And Result Types
- fn.decl.parameter-typesNamed functions must declare every parameter type.
- fn.decl.result-required-pubA public function, a public inherent method, a trait method, and a method of a trait implementation must also declare its result type. Omitting it is an error. Error:
missing-result-type. - fn.decl.result-omitted-privateA non-public function, a non-public inherent method, or a local
fndeclaration may omit-> type. - fn.decl.result-inferredIts result type is then inferred from its body, as for a nonrecursive closure.
- fn.decl.result-inferred.commonThe inferred result is the least common type of the body's final value and every
returnoperand. - fn.decl.result-inferred.voidThe inferred result is
voidwhen the body produces no value. - fn.decl.row-omittedSuch a function may also omit its requirement clause. Its row is then inferred as specified in Requirements and Suspension.
- fn.decl.suspension-not-inferredSuspension is never inferred: it is part of the function's name.
pub fn identity(x: i32): x # error: missing-result-type
struct Cart:
count: i32
impl Cart:
pub fn total(self): # error: missing-result-type
self.countWhy. Every signature that another file can see is written out. So a caller in another file never waits for a callee's body to be checked. Files can then be checked in parallel.
#Opaque Results
- fn.opaque.named-functionAny named function, including a trait declaration or implementation method, may declare an opaque result.
- fn.opaque.nestedA return annotation may contain multiple opaque type occurrences, including nested type arguments, tuples and optional types.
- fn.opaque.occurrence-same-typeFor each opaque occurrence, every value supplied at that occurrence must have the same hidden concrete type. Error:
type-mismatch. - fn.opaque.occurrence-no-joinDistinct hidden types at one occurrence are not joined or converted to choose a common hidden type.
- fn.opaque.occurrence-boundEach hidden concrete type must satisfy its occurrence's declared trait bound and associated-type bindings. Error:
unsatisfied-trait-bound.
#Recursion Without A Result Type
- fn.decl.omitted-recursionA function whose result type is omitted must not be recursive through functions whose result types are all omitted, itself included.
- fn.decl.omitted-cycleA cycle of functions with omitted result types that call each other, directly or through one another, is an error. Error:
recursive-function-needs-result-type. - fn.decl.omitted-cycle.reportThe error is reported once, on the member of the cycle that appears first in source order.
- fn.decl.omitted-cycle.resolveAdding a result type to any member of the cycle resolves it.
fn is_even(n: i32): # error: recursive-function-needs-result-type
if n == 0: true
else: is_odd(n - 1)
fn is_odd(n: i32):
if n == 0: false
else: is_even(n - 1)#Bodies And Control Paths
- fn.body.final-valueThe body's normal final value must be assignable to the declared or inferred result.
- fn.body.early-returnExplicit
returnmay complete the function earlier. - fn.body.pathsEvery reachable control path must do one of three things. It returns a value assignable to the declared result, falls through with such a final value, or completes abruptly by propagation or panic.
- fn.body.value-less-fallthroughA non-
voidfunction with a reachable value-less fallthrough is an error. Error:missing-return-value. - fn.body.infinite-loopA path that enters an infinite loop that no
breaktargets never completes, so it needs no value. - fn.body.void-finalA
voidfunction likewise rejects a non-voidfinal expression. Error:type-mismatch.
fn invalid(flag: bool) -> i32:
if flag: # error: missing-return-value
return 1Note. Use
return,pass, or anothervoidexpression when a preceding value is intentionally ignored.
#Function Names
- fn.name.uniqueFunction names are unique in their scope.
- fn.name.no-overloadinghd-lang has no function or method overloading: one name resolves to one declaration in its scope.
fn value(input: i32) -> i32: input
fn value(input: string) -> string: input # error: duplicate-module-name#Same-Line Bodies
- fn.body.same-lineA same-line body is permitted when it contains one simple statement.
fn test() -> void $ Console: println("hi")#Local Functions
A named function may also be declared inside an executable block suite:
fn total_with_bonus(values: List[i32], bonus: i32) -> i32:
fn add_bonus(value: i32) -> i32:
value + bonus
let total: i32 = 0
for value in values:
total = total + add_bonus(value)
total- fn.local.declareA named function may be declared inside an executable block suite.
- fn.local.scopeIts name is visible from that declaration onward and within its own body.
- fn.local.capture-rulesIt can capture enclosing local values under the same capture rules as a closure.
- fn.local.privateIt cannot be marked
pubor used from another module.
See also: Captures.
#Parameters
This section defines how parameters are initialized and passed.
fn inspect(user: User) -> string: user.name
fn rename(user: &mut User, name: string) -> void:
user.name = name- fn.param.init-orderParameters are evaluated and initialized from left to right after argument mapping.
- fn.param.fixedA parameter that is not
mutis a non-reassignable binding: its name cannot be reassigned. Reassigning one is an error. Error:non-reassignable-parameter-binding. - fn.param.primitivePrimitive parameters pass by value.
- fn.param.value-copyEvery other parameter that is not a reference passes by value too. The callee gets its own copy of a struct, tuple, enum, list, or map argument.
- fn.param.referenceA
&Tparameter passes a reference, through which the callee reads the caller's place or object. Through a&mut Tparameter it may also write. - fn.param.no-transferhd-lang does not perform ownership transfer at a call.
- fn.param.mut
mutbefore a parameter name, as inmut a: S, marks the callee's own copy of the argument, which may change. - fn.param.mut.copyThe argument moves into a
mutparameter at the caller's last use of it, and is copied otherwise. The caller's value is unchanged unless the callee returns the copy and the caller keeps it. - fn.param.mut.reassignA
mutparameter may be reassigned as a whole, and a struct field of one is a writable place. - fn.param.mut.binding
mut a: Tmarks the binding, not the type, somut a: Swith a structSis valid anda: mut Sis the syntax error ofgrammar.type.no-mut. - fn.param.mut.closureA closure parameter may be
mutin the same way.
fn normalize(value: i32) -> i32:
value = 0 # error: non-reassignable-parameter-binding
valuestruct Counter:
n: i32
fn bumped(mut c: Counter) -> Counter:
c.n += 1 # changes the copy, which is returned
c
fn bump(mut c: Counter) -> void:
c.n += 1 # changes only the copy: the caller's value is unchangedNote. A
mutparameter never changes the caller's value in place. A reference parameter,&mut T, does; Values And References states the syntax.
#Positional And Named Arguments
A call may mix positional and named arguments:
resize(640, height=480)- fn.arg.mixCalls may mix positional and named arguments.
- fn.arg.positional-firstPositional arguments must come first.
- fn.arg.positional-after-namedA positional argument must not follow a named argument.
- fn.arg.labelsNamed argument labels are parameter names and are part of the source-level calling interface.
- fn.arg.unknown-nameA named argument that names no parameter is an error. Error:
unknown-named-argument. - fn.arg.onceA parameter must receive one value, either explicitly or from its default.
- fn.arg.duplicateSupplying a parameter more than once is an error. Error:
duplicate-argument.
fn resize(width: i32, height: i32) -> i32: width * height
fn area() -> i32: resize(640, depth=480) # error: unknown-named-argument
fn twice() -> i32: resize(640, width=480) # error: duplicate-argument#Default Values
A parameter may declare a default:
fn connect(host: string, port: i32 = 443, tls: bool = true) -> Connection:
...- fn.default.allowedA parameter may declare a default.
- fn.default.order-final-functionAfter the first parameter with a default, every following non-vararg parameter must also have a default. The one exception is a final parameter whose type is a function type, or a type parameter bounded by a zero-argument
FnorFnMutas infn.trailing.fn-bound. A later parameter without one is an error. Error:default-order. - fn.default.omitCalls may omit only parameters that have defaults.
- fn.default.evalDefaults are evaluated for each call, in parameter declaration order, after all explicit argument expressions have been evaluated.
- fn.default.scopeA default may refer to earlier parameters but not later parameters.
- fn.default.later-parameterA default that names a later parameter is an error. Error:
binding-not-yet-visible. - fn.default.final-functionA call may supply such a final function-typed parameter by a trailing block or a named argument, and omit the defaulted parameters before it.
- fn.default.observable-effectsThe observable effects of a default must occur on every call that omits its argument, even when its result is constant.
fn retry(times: i32, backoff: i32 = 100, body: fn() -> void) -> void:
body()
fn run() -> void:
retry(3):
pass
retry(3, backoff=10):
pass
retry(3, body=fn(): pass)Why. As in Kotlin and Swift, defaulted options may come before a trailing body. A trailing block or a named argument always reaches the final parameter.
#Requirement-Free Defaults
- fn.default.requirement-freeA default expression must be requirement-free: it must not use a provider and must not suspend.
- fn.default.requirement-free.syntaxConcretely, it must not contain
$.use, a provider scope, or a bang call. - fn.default.requirement-free.callsEvery function, method, closure, or function value it calls must have an empty requirement row.
- fn.default.requirement-free.signaturesThe check reads only signatures, never function bodies, because both properties are part of every callable's type.
- fn.default.requirement-free.uniformThe check applies equally to named functions, function values, and dynamic trait methods.
- fn.default.effectsA default may otherwise evaluate any expression, including calls that mutate state.
- fn.default.providerA default that uses a provider, in a parameter, struct field, or shared enum constructor parameter, is an error. Error:
requirement-in-default. - fn.default.suspendsA default that suspends is an error. Error:
suspension-forbidden-context.
trait Clock:
fn now(self) -> i32
fn current_time() -> i32 $ Clock:
$.use(Clock).now()
fn wait!() -> i32: 1
fn bad(first: i32 = 1, second: i32) -> i32: second # error: default-order
fn span(start: i32 = finish, finish: i32 = 10) -> i32: finish - start # error: binding-not-yet-visible
fn stamp(time: i32 = current_time()) -> i32 $ Clock: time # error: requirement-in-default
fn late(value: i32 = wait!()) -> i32: value # error: suspension-forbidden-contextNote. Because defaults run after all explicit arguments, in parameter declaration order, the effects of a default are ordered.
#Varargs
A final positional parameter may write ... after its name. It collects
the call's remaining positional arguments into its declared type:
fn sum(values...: List[i32]) -> i32:
...- fn.vararg.formA final positional parameter may write
...after its name, as invalues...: List[i32]. It is then a vararg. - fn.vararg.typeThe type after
:is the parameter's type inside the body, as for any parameter, sovaluesabove is aList[i32]. - fn.vararg.type.kindsA vararg whose type is not
List[T], a tuple type, or a type parameter bounded byTupleis an error. Error:type-mismatch. - fn.vararg.collectA call supplies a vararg zero or more separate positional arguments, which are collected into its type, or one positional spread of that type.
sum()
sum(1, 2, 3)
sum(items...)- fn.vararg.collect.listFor
List[T], each argument is checked againstT, and the list holds the arguments in order. - fn.vararg.collect.tuple-exprFor a tuple type, the arguments are collected exactly as the tuple expression of them, against that type, by Tuple Expressions and Tuple Rest Elements. So
call(g, 1, 2, xs...)collects(1, 2, xs...). Error:type-mismatch. - fn.vararg.tuple-param.expectedAnother argument may solve the vararg's
Tuple-bounded type parameter, asfsolvesArgsbelow. Then the vararg's arguments are checked against that solved tuple as an expected type. - fn.vararg.tuple-param.inferWhen no other argument solves it, inference solves it as the tuple of the argument types, one element per argument, with no join.
- fn.vararg.no-auto-spreadA tuple argument is never spread automatically: it is one element of the collected tuple.
use std.function.{Fn, Tuple}
fn add2(a: i32, b: i32) -> i32: a + b
fn neg(a: i32) -> i32: -a
fn zero() -> i32: 0
fn g(a: usize, b: usize, xs...: List[i32]) -> usize: a + b + xs.len()
fn call[Args < Tuple, O, $R](f: Fn[Args, O, $ R], args...: Args) -> O $ R:
f(args...)
fn pack[Args < Tuple](args...: Args) -> Args: args
fn run(pair: (i32, i32)) -> i32:
call(add2, 1, 2) + call(neg, 5) + call(zero) + call(add2, pair...)
fn tail(xs: List[i32]) -> usize: call(g, 1, 2, 3, 4) + call(g, 1, 2, xs...)| Call | Args |
|---|---|
call(add2, 1, 2) |
(i32, i32), from add2 |
call(neg, 5) |
(i32,) |
call(zero) |
() |
call(add2, pair...) |
(i32, i32), which the spread matches |
call(g, 1, 2, 3, 4) |
(usize, usize, List[i32]...), from g; 3 and 4 form the rest |
call(g, 1, 2, xs...) |
(usize, usize, List[i32]...), from g; xs is the rest |
call(add2, (1, 2)) |
(i32, i32), which the one argument (1, 2) does not fill |
pack(1, "a") |
(i32, string), from the arguments |
- fn.vararg.finalA vararg that is not the last positional parameter is an error. Error:
nonfinal-vararg. - fn.vararg.no-defaultA vararg has no default expression.
- fn.vararg.namedPassing a vararg by name passes its collected value without spread syntax, as in
sum(values=[1, 2])orcall(add2, args=(1, 2)).
A function value keeps a List[T] vararg, as Vararg Inputs
states:
fn count(values...: List[i32]) -> usize: values.len()
fn main() -> usize:
f := count
f(3, 4, 5)Open in playgroundHere f has type fn(List[i32]...) -> usize.
use std.function.{Fn, Tuple}
fn scaled(values...: List[i32], factor: i32) -> i32: factor # error: nonfinal-vararg
fn count(values...: i32) -> i32: values # error: type-mismatch
fn apply(callback: fn(i32...) -> i32) -> i32: 0 # error: type-mismatch
fn add2(a: i32, b: i32) -> i32: a + b
fn call[Args < Tuple, O, $R](f: Fn[Args, O, $ R], args...: Args) -> O $ R: f(args...)
fn nested() -> i32: call(add2, (1, 2)) # error: type-mismatchWhy. Declaring
args...mirrors spreadingargs.... The type after:is the type the body sees, so a vararg needs no type rule of its own. AList[T]vararg shows in the function's type as a rest element, so a function value keeps its varargs.
See also: Positional Spreads.
#Function Types And Values
Functions are values. A plain function type lists parameter types and a result:
fn(string) -> string
fn!(UserId) -> Result[User, DbError] $ Database- fn.type.valuesFunctions are values.
- fn.type.formA plain function type lists parameter types and a result.
- fn.type.no-namesParameter names and default values are not part of a function value type.
- fn.type.positionalCalling through a function value therefore uses positional arguments only and does not inherit declaration defaults.
- fn.type.positional.namedA named argument in a call through a function value names no parameter, so it is an error. Error:
unknown-named-argument. - fn.type.partsSuspension and requirement rows are part of the type.
#Function Type Constructors
Every function type is exact sugar for one of two standard constructors that
std.function declares:
| Sugar | Constructor form |
|---|---|
fn(A, B) -> O $ R |
Fn[(A, B), O, $ R] |
fn!(A, B) -> O $ R |
SuspendFn[(A, B), O, $ R] |
fn(A) -> O |
Fn[(A,), O, $()] |
fn() -> O $ Db + Cache |
Fn[(), O, $ Db + Cache] |
use std.function.{Fn, SuspendFn}
trait Database
fn check(id: i32, name: string) -> bool: id > 0
fn load!(id: i32) -> string $ Database: "user"
fn spelled() -> Fn[(i32, string), bool, $()]:
check
fn sugared(callback: Fn[(i32, string), bool, $()]) -> fn(i32, string) -> bool:
callback
fn suspending() -> SuspendFn[(i32,), string, $ Database]:
load
fn invoke[F < Fn(i32) -> i32](f: F, value: i32) -> i32:
f(value)
fn invoke_tuple[F < Fn[(i32,), i32, $()]](f: F, value: i32) -> i32:
f.call((value,))- fn.type.ctor.decl.contextualIn type positions,
std.functiondeclaresFn[I, O, $R]andSuspendFn[I, O, $R]as plain and suspending function type constructors. - fn.type.ctor.inputsThe inputs argument is one tuple type whose elements are the parameter types, such as
(),(A,), or(A, B). It may also be a type parameter bounded byTuple. - fn.type.ctor.no-flattenA tuple is never flattened into parameters:
Fn[((A, B),), O, $ R]takes one pair, andFn[(A, B), O, $ R]takes two values. - fn.type.ctor.rowThe row argument is row-kinded. A function type without a requirement clause has the empty row
$(), and several keys are joined with+, as in$ Db + Cache. - fn.type.ctor.row.dollarThe row argument is a row slot, so one key or a row alias is written after
$too, as inFn[(), O, $ Db]andFn[(), O, $ AppRow]. A bare one is an error. Error:generic-kind-mismatch. - fn.type.ctor.tuple-trait
std.functionalso declaresTuple, an empty sealed marker trait that every tuple type implements,()and(A,)included. - fn.type.ctor.tuple-trait.restA tuple type with a rest element is a tuple type and implements
Tuple, soArgsmay be(i32, List[i32]...). - fn.type.ctor.inputs-tupleAn inputs argument that is not a tuple type or a type parameter bounded by
Tupleis an error. Examples areFn[i32, i32, $()], andFn[Args, O, $ R]with an unboundedArgs. Error:generic-kind-mismatch. - fn.type.ctor.sugar
fn(A) -> O $ RandFn[(A,), O, $ R]denote the same type, and so dofn!(A) -> O $ RandSuspendFn[(A,), O, $ R]. - fn.type.ctor.anywhereEither spelling is valid anywhere a type may appear, including implementation targets.
- fn.type.ctor.diagnosticsDiagnostics print a function type in its sugar form, as they print
T?forOption[T]. - fn.type.ctor.importsThe sugar needs no import. The names
Fn,SuspendFn, andTupleare imported where they are written, as inuse std.function.Fn. - fn.type.ctor.opaque-sourcesThe constructors have no fields and no construction syntax. Function values come only from function names, closures, one-payload variant constructors, instantiated generic functions, and method references.
use std.function.{Fn, Tuple}
trait Describe:
fn describe(self) -> string
impl[Args < Tuple, O, $R] Describe for Fn[Args, O, $ R]:
fn describe(self) -> string: "function"
fn invalid(callback: Fn[i32, i32, $()]) -> void: pass # error: generic-kind-mismatch
fn unbounded[Args, O](callback: Fn[Args, O, $()]) -> void: pass # error: generic-kind-mismatch#Static Fn Bounds
The Fn trait describes the exact plain function type that a generic value
may hold and call.
- fn.trait.decl
std.functiondeclarestrait Fn[I < ?Copy & Tuple, O < ?Copy, $R = $()]withfn call(&self, args: I) -> O $R. - fn.trait.function-values-read-onlyA plain function value implements
Fnfor its exact inputs tuple, output type, and requirement row, except wherefn.trait.read-onlyand the rules after it make it implement onlyFnMut. - fn.trait.bound-sugarIn a bound,
Fn(A, B) -> O $RdenotesFn[(A, B), O, $R], and an omitted row is$(). - fn.trait.bound-tupleThe tuple form
Fn[(A, B), O, $R]remains valid in a bound. - fn.trait.callA value of type parameter
F < Fn(A, B) -> O $Rmay be called asf(a, b)and requires$R. - fn.trait.suspend-weakenA suspending function value
fn!(A, B) -> O $RsatisfiesF < Fn(A, B) -> Suspend[O] $Rthrough the same weakening as an expected concrete plain function type. - fn.trait.bound.infer-instantiationCall inference solves an
Fnbound's input tuple, output and requirement-row arguments from a concrete function value's oneFninstantiation, including a suspending function's weakened instantiation. - fn.trait.bound.closure-inputsAn unannotated closure passed to a bare parameter
Ftakes its parameter types fromF'sFnbound when those input types are known; the closure's concrete type still solvesF. - fn.trait.bound-closureA closure or a concrete function value passed to a bare parameter
Fhas the signature ofF'sFnorFnMutbound, its row included. Another signature is an argument error, and the bound itself reports nothing more. Error:type-mismatch. - fn.trait.bound-sugar.next-boundIn a bound list,
&after the sugar's result type starts the next bound. SoF < Fn() -> void & 'aisFn() -> voidand'a(Lifetime Bounds). - fn.trait.no-dyn
FnandFnMutare the two traits with nodyntype, asref.type.dyn.no-fnstates. Error:invalid-dyn-type.
Why. The concrete
fn(...)type remains the dynamic function value.Fn(...)gives stored callbacks static dispatch without a second dynamic form.
#FnMut Bounds
The FnMut trait describes a generic function value whose calls may change
its captures, as Rust's FnMut does.
use std.function.{Fn, FnMut}
fn twice[F < FnMut(i32) -> void](mut f: F) -> void:
f(1)
f.call_mut((2,))
fn forward[F < Fn(i32) -> void](f: F) -> void:
twice(f)
fn stuck[F < FnMut(i32) -> void](f: F) -> void:
f(1) # error: not-writable- fn.trait.mut.decl
std.functiondeclarestrait FnMut[I < ?Copy & Tuple, O < ?Copy, $R = $()]withfn call_mut(&mut self, args: I) -> O $R. - fn.trait.mut.supertrait
Fn[I, O, $R]has the supertraitFnMut[I, O, $R], so a value whose bound isFnmeets anFnMutbound of the same arguments. - fn.trait.mut.function-valuesEvery plain function value implements
FnMutfor its exact inputs tuple, output type, and requirement row. - fn.trait.mut.sugar
FnMut(A, B) -> O $RdenotesFnMut[(A, B), O, $R], and the bound rules forFnabove apply toFnMutalike. - fn.trait.mut.callA value of type parameter
Fwhose bound isFnMutand notFnmay be called asf(a, b). The call changesf, sofmust be a writable place or a temporary. Error:not-writable. - fn.trait.mut.not-fnA type parameter bounded by
FnMutonly does not meet anFnbound. Error:unsatisfied-trait-bound.
Why. A callee that only reads through its function value takes
Fn. One that lets the value change its state, as an iterator adapter does, takesFnMutand calls it through a writable copy.
#Read-Only Fn Closures
A value passed or stored for a type parameter bounded by Fn may not change
its captures, as Rust's Fn closures may not.
use std.function.{Fn, FnMut}
fn check[F < Fn() -> bool](condition: F) -> bool:
condition()
fn each[F < FnMut(i32) -> void](items: List[i32], mut f: F) -> void:
for item in items:
f(item)
fn ready() -> bool: true
fn demo(test: fn() -> bool) -> void:
let count = 0
check(fn(): count < 3)
check(ready)
each([1, 2], fn(x): count += 1)
check(
fn(): # error: not-writable
count += 1
true
,
)
_ := check(test) # error: unsatisfied-trait-bound- fn.trait.read-onlyA closure that changes a captured local implements
FnMutbut notFn. Writing one where a type parameter bounded byFnis expected is an error. Error:not-writable. - fn.trait.read-only.changesA closure changes a captured local when its body assigns the local or one of its fields, takes
&mutof it, changes it as a collection, or calls it as anFnMutvalue. A closure nested in the body counts too. - fn.trait.read-only.throughA store through a captured local
&mutreference changes that capture too. A store through a captured counted*mut Tdoes not. - fn.trait.read-only.itemsA function name, a variant constructor, an unbound method reference, and a closure that changes no capture implement
Fn. - fn.trait.read-only.bound-refA bound method reference implements
Fnunless it changes its receiver: a&mut selfmethod, or a list'spushor a map'sremove. Such a reference for anFnbound is an error. Error:not-writable. - fn.trait.read-only.valuesAny other value of a concrete
fn(...)type implements onlyFnMut, since its body may change its captures. Passing one for anFnbound is an error. Error:unsatisfied-trait-bound. - fn.trait.read-only.positionsThese rules apply to a positional or named call argument for a bare type parameter, and to a struct literal field whose type is a bare type parameter.
- fn.trait.read-only.concreteA concrete
fn(...)parameter takes either kind of value, so a closure passed for one may change its captures.
#Vararg Inputs
A function with a List[T] vararg has inputs that end in the
rest element List[T]..., and its
function value keeps the vararg:
fn g(a: usize, b: usize, xs...: List[i32]) -> usize: a + b + xs.len()
fn h(a: usize, b: usize, xs: List[i32]) -> usize: a + b + xs.len()
fn apply(callback: fn(usize, usize, List[i32]...) -> usize) -> usize:
f := g
f(1, 2, 3, 4) + callback(1, 2) + h(1, 2, [3, 4])| Function | Type | Constructor form |
|---|---|---|
g |
fn(usize, usize, List[i32]...) -> usize |
Fn[(usize, usize, List[i32]...), usize, $()] |
h |
fn(usize, usize, List[i32]) -> usize |
Fn[(usize, usize, List[i32]), usize, $()] |
- fn.type.vararg-restA
List[T]vararg is the rest elementList[T]...of its function's inputs tuple. Sogabove has typefn(usize, usize, List[i32]...) -> usize, which differs fromh's type. - fn.type.rest-callCalling a function value whose inputs end in a rest element
List[T]...treats that element as aList[T]vararg, as inf(1, 2, 3, 4)above. - fn.type.tuple-vararg-inputA vararg whose type is a tuple type or a
Tuple-bounded type parameter is one ordinary input of its function's type. That input takes the collected tuple.callhas typefn(Fn[Args, O, $ R], Args) -> O $ R.
fn sum(values...: List[i32]) -> i32: values[0]
fn apply_pair(callback: fn(i32, i32) -> i32) -> i32: callback(1, 2)
fn apply_list(callback: fn(List[i32]) -> i32) -> i32: callback([1, 2])
fn first() -> i32: apply_pair(sum) # error: type-mismatch
fn second() -> i32: apply_list(sum) # error: type-mismatch#No Access Permission
- fn.type.no-permissionA function value carries no access permission, and calling one never needs mutable access to it.
- fn.type.no-mut
mutapplied to a function type, as inmut (fn() -> i32)ormut Fn[(), i32, $()], is an error. Error:syntax-error. - fn.type.no-mut.syntax
mutwritten directly beforefn, in a type or a closure header, is an error. Error:syntax-error.
fn counter() -> mut fn() -> i32: # error: syntax-error
fn() -> i32: 1Why. A function value has no fields to take a permission on. A closure may mutate its captures freely, so the type needs no mutation capability.
#Passing Function Values
- fn.type.named-valueA named function value may be passed anywhere its function type is expected.
- fn.type.variant-valueSo may a variant constructor with exactly one payload field, such as
SyncError.Fsof typefn(FsError) -> SyncError. - fn.type.declared-varianceFunction types follow the declared variance of
FnandSuspendFn: contravariant in each input element, covariant in the output, and invariant in the row. - fn.type.variance-reprLike every variance conversion, a function-type conversion must be representation-preserving.
- fn.type.variance-repr.excludedTrait-value construction and optional injection therefore never convert a parameter or result of a function type. Error:
variance-representation-change.
fn count() -> *i32: box(1)
fn erase() -> fn() -> *dyn Display:
count # error: variance-representation-changeWhy. The polarity rules of Variance already treat parameters as negative and results as positive. Declaring that variance on the constructors removes a special case.
Note. A function value also fits a function type whose row is wider than its own. That is row subsumption, not a variance conversion, and it may adapt the value.
See also: Enum Declarations, Representation-Preserving Variance.
#Lifetimes In Function Types
A function type's result may hold a local reference that borrows from its inputs, as a function's result may:
struct User:
name: string
fn name_of(u: &User) -> &string:
&u.name
fn longer['a](a: &'a User, b: &'a User) -> &'a User:
if a.name.len() >= b.name.len(): a else: b
fn apply(f: fn(&User) -> &string, u: &User) -> usize: # depends on its one input
f(u).len()
fn pick['a](f: fn(&'a User, &'a User) -> &'a User, a: &'a User, b: &'a User) -> usize:
f(a, b).name.len()
fn demo(a: &User, b: &User) -> usize:
apply(name_of, a) + pick(longer, a, b) + apply(fn(u): &u.name, b)- fn.type.lifetime.resultA function type's result may hold a local reference, as a dependent result of a function may.
- fn.type.lifetime.positionEach
&or&mutin a function type's inputs and in its result is a reference position of that type. - fn.type.lifetime.writtenA reference position may write a lifetime variable of the enclosing declaration, and positions that write one variable share its lifetime.
- fn.type.lifetime.no-binderA function type declares no lifetime parameters of its own.
- fn.type.lifetime.elideA result position that writes no lifetime takes the one lifetime of the input positions.
- fn.type.lifetime.elide.noneSuch a position with no input reference position is an error. Error:
reference-result-without-source. - fn.type.lifetime.elide.ambiguousSuch a position under two or more lifetimes of the input positions is an error. Error:
ambiguous-reference-source. - fn.type.lifetime.identityWhich input positions each result position depends on is part of the function type, and the names of its lifetime variables are not.
- fn.type.lifetime.subtypeA function value fits when each result depends on a subset of the input positions that the expected result permits.
- fn.type.lifetime.subtype.errorA result that depends on an input position the expected result does not permit is an error. Error:
type-mismatch. - fn.type.lifetime.valueA named function's or method's value has the dependencies of its signature, after elision, with an unbound method's receiver as its first input.
- fn.type.lifetime.callA call through a function value depends on what its arguments in each result position's lifetime depend on, as
ref.lifetime.callstates for a named call. - fn.type.lifetime.call.writtenA call through a function value passes the argument for an input position that writes a lifetime variable at that lifetime, which the argument must outlive, whatever the result holds. The written lifetime goes with the value through bindings, fields, captures and a call's result, and passing the value for a parameter whose type writes a lifetime there makes that lifetime the value's. A call through a field is checked against the field's type: the function value stored in it never widens what that type allows. A call's lifetime is at least each lifetime of the arguments the call passes at it. With
f: fn(&'a Point) -> T,f(&q)andg := f; g(&q)of a localqare errors. So is(relay(Holder { f: x_of }, p).f)(&q)withrelay['a, T](h: Holder['a, T], p: &'a Point) -> Holder['a, T], thoughx_ofwrites no lifetime. Error:local-reference-escapes. - fn.type.lifetime.call.written.closureA closure parameter's type may write a lifetime of the enclosing function. The closure's value then writes it at that input position, and the parameter has that lifetime in the closure's body. So
(fn(x: &'a Point): x.x)(&q)of a localqis an error. Error:local-reference-escapes. - fn.type.lifetime.result.paramA type parameter in a function type's result may hold the lifetimes of its input positions. An instance whose result holds a reference may depend on each input position that writes a lifetime and on those that
fn.type.lifetime.result.param.positionnames, and on no other. A call passing a function value for that type depends on what its arguments at those lifetimes depend on. Withgood['a, T](f: fn(&'a Point) -> T, p: &'a Point) -> T,good(ident, p)withident(x: &Point) -> &Pointis a&Pointthat depends onp. - fn.type.lifetime.result.param.positionA result position that a type parameter fills depends on the input positions that the same parameter fills at the same position of its type argument, and on no other. With
T = (&'a A, &'b B),fn(T) -> Tisfn((&'a A, &'b B)) -> (&'a A, &'b B): its result's first element depends on its input's first element, and its second on its second. Withapp[T](f: fn(T) -> T, x: T) -> T,app(ident, p)is a&Pointthat depends onp, and withfn(T, U) -> Tat&Pointfor both, a function returning its second input is an error. Error:type-mismatch.
struct User:
name: string
fn left['a, 'b](a: &'a User, b: &'b User) -> &'a User:
a
fn run['a](f: fn(&'a User, &'a User) -> &'a User, u: &'a User) -> usize:
f(u, u).name.len()
fn either['a](a: &'a User, b: &'a User) -> &'a User:
if a.name.len() >= b.name.len(): a else: b
fn use_left['a, 'b](f: fn(&'a User, &'b User) -> &'a User, a: &'a User, b: &'b User) -> usize:
f(a, b).name.len()
fn demo(a: &User, b: &User) -> usize:
run(left, a) + use_left(either, a, b) # error: type-mismatch
fn apply(f: fn(&User, &User) -> &User) -> void: # error: ambiguous-reference-source
pass
fn make(f: fn() -> &User) -> void: # error: reference-result-without-source
passWhy. These are Rust's elision rules, applied inside the function type. Without a binder of its own, a written lifetime is the enclosing declaration's, as in Rust, and a lifetime adds nothing at run time. A function type that needs its own variables, as a struct field's type may, comes with stored references. A value that borrows from fewer inputs satisfies every lifetime promise of one that may borrow from more.
A type parameter is replaced position for position, as Rust substitutes it, so filling
Twith a tuple of references gives each element its own lifetime instead of one lifetime for all ofT.
See also: Lifetime Variables, Closure Annotations.
#Generic Function Values
A generic function passed as an argument takes its type arguments from the call:
fn identity[T](value: T) -> T:
value
fn apply[A, B](value: A, f: fn(A) -> B) -> B:
f(value)
count := apply(+3, identity)- fn.type.generic.not-polymorphicGeneric functions are not first-class polymorphic values.
- fn.type.generic.instantiate-everyReferring to one as a value must instantiate every generic parameter.
- fn.type.generic.instantiate-fromThe type arguments come from an expected monomorphic function type, from an explicit type-argument list, or from the call the value is an argument of.
- fn.type.generic.placeholderA placeholder in that list may be solved from the expected monomorphic type.
- fn.type.generic.argumentWhen the value is an argument of a call, its type arguments are solved together with the call's other type variables.
- fn.type.generic.argument.sourcesThose variables are solved from the other arguments, the expected result type, and the called function's constraints, as for the call itself.
- fn.type.generic.defaultA parameter that those sources leave unsolved takes its default, as at a call. For
fn empty[C = List[i32]]() -> C,make := emptyhas typefn() -> List[i32]. - fn.type.generic.unsolvedA generic parameter of the value that remains unsolved is an error. Error:
cannot-infer-type. - fn.type.generic.monomorphicThe resulting value has an ordinary monomorphic function type.
In count := apply(+3, identity), A is i32 from the first argument, and
identity's T and the call's B are solved as i32 with it.
fn identity[T](value: T) -> T:
value
fn call_with_nothing[A, B](f: fn(A) -> B) -> void:
pass
fn main() -> void:
call_with_nothing(identity) # error: cannot-infer-typeOpen in playgroundWhy. Only use sites infer. A function declaration's own generic parameters and signature are always written, never inferred from its body or its callers.
See also: Type Inference Boundaries, Variant Constructors As Function Values.
#Suspending Function Values
- fn.type.suspend.callA value of type
fn!(A) -> T $ RconstructsSuspend[T]when called normally. - fn.type.suspend.bangIt may be bang-called inside a suspending body.
- fn.type.suspend.weakenIt may be weakened to the lowered constructor type
fn(A) -> Suspend[T] $ R. - fn.type.suspend.no-reverseThe reverse conversion is not implicit.
- fn.type.suspend.ctorIn constructor form, the weakening converts
SuspendFn[I, O, $ R]toFn[I, Suspend[O], $ R].
fn fetch!(key: string) -> string: "value of $key"
fn store() -> void:
_ := fetch("k1") # a Suspend[string]; nothing has run#Method References
A method reference names a method or an associated function as a function value. It is the qualified call without its arguments:
struct Counter:
value: i32
impl Counter:
fn bump(&mut self, by: i32) -> void:
self.value = self.value + by
fn read(self) -> i32:
self.value
fn zero() -> Counter:
Counter { value: 0 }
fn reader() -> fn(Counter) -> i32:
Counter::read
fn maker() -> fn() -> Counter:
Counter::zero
fn bumper(counter: *mut Counter) -> fn(i32) -> void:
counter::bump-
fn.ref.unbound
Owner::namewithout an argument clause, whereOwnernames a type, a trait, or a type parameter, is an unbound method reference. -
fn.ref.unbound.receiverFor a method, the reference takes the receiver first, then the method's own parameters:
Counter::bumphas typefn(&mut Counter, i32) -> void. -
fn.ref.unbound.value-selfA
selfmethod gives aSelffirst parameter, and so does themut selfmethod of a struct, a list or a map. -
fn.ref.unbound.ref-selfA
&selfmethod gives a&Selffirst parameter, and a&mut selfmethod a&mut Selfone. -
fn.ref.associatedFor an associated function, the parameters are the function's own:
Counter::zerohas typefn() -> Counter. -
fn.ref.lookupA reference resolves
nameas the qualified callOwner::name(...)does. That is inherent members of a type first, then its available traits, and a type parameter through its bounds. -
fn.ref.lookup.ambiguousTwo trait candidates for one name are an error. Error:
ambiguous-method. -
fn.ref.trait-selfFor
Trait::name,Selfis inferred from the expected function type, as a generic function value's parameters are. -
fn.ref.trait-self.unsolvedA trait reference whose
Selfnothing determines is an error. Error:cannot-infer-type. -
fn.ref.genericA generic member's reference writes its type arguments after the name, as in
Json::decode::[User], and the owner's before the member's::, as inBox::[i32]::get. -
fn.ref.generic.instantiateEvery type parameter of the member is instantiated as for a generic function value.
-
fn.ref.bound
value::name, wherevaluenames a value rather than a type or trait, is a bound method reference. -
fn.ref.bound.captureIt evaluates
valueonce, when the reference is created, and captures that receiver. Calling the reference later calls the method on the captured receiver, whatevervaluenames by then. -
fn.ref.bound.typeIts parameters are the method's own, without the receiver:
counter::bumphas typefn(i32) -> void. -
fn.ref.bound.addressA bound reference to a
&selfor&mut selfmethod takes the receiver's address when it is created, as a call does. Calling it later reads or changes that place. -
fn.ref.bound.address.writableA bound reference to a
&mut selfmethod needs a writable place or a&mutreference as its receiver, as the call does. Error:not-writable. -
fn.ref.callA reference followed by an argument clause is an ordinary call, so
user::domain()callsdomainonuser. -
fn.ref.suspendingA suspending method is referenced without
!, asStore::load, and the reference has a suspending function type such asfn!(Store, Key) -> Blob. -
fn.ref.valueA reference is an ordinary function value: it has no parameter names or defaults, and it carries the member's row and suspension.
-
fn.ref.no-fields
::names only methods and associated functions, never fields.User::emailfor a fieldemailis an error. Error:unknown-method. -
fn.ref.bound.associatedA bound reference names a method, since an associated function has no receiver to bind.
counter::zerofor an associated functionzerois an error. Error:unknown-method. -
fn.ref.dynamic.reference-receiverA trait method reference may take a trait value reference as its first parameter and dispatches through its vtable.
-
fn.ref.dynamic.bound-referenceA bound method reference on a trait value reference captures that reference once and calls the method on its place.
-
fn.ref.dynamic.permissionA method reference retains the receiver permission a direct call requires. A mutating method needs
&mut dyn, and a reference to it through&dynis an error. Error:not-writable.
Note. The writable-place comparison concerns calls on existing places. Temporary receiver calls are separate from bound references, which follow
fn.ref.bound.address.writable.
struct Counter:
value: i32
impl Counter:
fn bump(&mut self, by: i32) -> void:
self.value = self.value + by
fn zero() -> Counter:
Counter { value: 0 }
struct User:
email: string
fn emails() -> fn(User) -> string:
User::email # error: unknown-method
fn frozen(counter: Counter) -> fn(i32) -> void:
counter::bump # error: not-writable
fn restart(counter: Counter) -> fn() -> Counter:
counter::zero # error: unknown-methodWhy. A reference reads as the call it stands for, as in Rust, Java, and Go. A bound reference fixes its receiver when it is made, as Kotlin and Go method values do. A closure such as
fn(): counter.read()instead reads the variable when it runs. Fields stay closures, so a field and a method may share a name without a clash.
See also: Associated Function Calls, Trait-Qualified Calls.
#Closures
A closure uses fn without a name:
initial := fn(text: string) -> string:
text.slice(0, 1)- fn.closure.formA closure uses
fnwithout a name. - fn.closure.no-other-syntaxThere is no separate arrow or shorthand-argument closure syntax.
- fn.closure.one-lineA one-line closure uses the same
:suite syntax.
inc := fn(x: i32) -> i32: x + 1- fn.closure.monomorphicA closure declares no type parameters and always has a monomorphic function type.
- fn.closure.monomorphic.sourcesIts parameter and result types come from its annotations or from the expected function type, as Closure Annotations states.
- fn.closure.no-type-parametersA closure header has no place for a type-parameter list, so
fn[T](x: T): xis an error. Error:syntax-error.
fn run() -> i32:
same := fn[T](value: T) -> T: value # error: syntax-error
0Why. A closure is a value, and generic functions are not first-class polymorphic values (
fn.type.generic.not-polymorphic). A method reference is instantiated the same way (fn.ref.generic.instantiate).
#Suspending Closures And Clauses
A suspending closure places ! after fn:
loader := fn!(id: UserId) -> Result[User, DbError] $ Database:
db := $.use(Database)
db.load_user!(id)- fn.closure.suspendingA suspending closure places
!afterfn. - fn.closure.requirementsA requirement clause follows its result type.
- fn.closure.clause-ownerThe clause directly before a header's
:always belongs to the function or closure being declared, even when its result is a function type. - fn.closure.clause-groupedA returned function type with its own row is parenthesized, as in
fn make() -> (fn() -> i32 $ Log) $ Console:.
See also: Types.
#Closure Annotations
When an expected function type is available, an inline closure may omit parameter and result annotations:
fn apply_all(values: List[i32], transform: fn(i32) -> i32) -> List[i32]:
[for value in values => transform(value)]
doubled := apply_all(counts, fn(count): count * 2)- fn.closure.annotations-omittedWhen an expected function type is available, an inline closure may omit parameter and result annotations.
- fn.closure.needs-annotationWithout a sufficient expected type, parameters must be annotated. An unannotated parameter is then an error. Error:
closure-parameter-needs-annotation. - fn.closure.result-inferredA nonrecursive closure may infer its result type from its body.
- fn.closure.result-inferred.commonThe inferred result is the least common type of the body's final value and every
returnoperand. When they have no common type, the closure is an error. Error:no-common-type. - fn.closure.result-expectedAn expected function type may instead supply the result type.
- fn.closure.recursive-resultA recursive local closure must always write its result type explicitly, even if an expected function type could supply it. Error:
recursive-function-needs-result-type. - fn.closure.lifetimeA closure's result position depends on the expected function type's input positions, or without one, on what its parameters' types elide as a function type would.
- fn.closure.lifetime.returnEach value a closure returns may depend only on the closure's parameter positions of each result position's lifetime. Error:
local-reference-escapes.
struct User:
name: string
fn run() -> i32:
closure := fn(value) -> i32: value # error: closure-parameter-needs-annotation
0
fn other_name(u: &User) -> usize:
local := User { name: "x" }
f := fn(v: &User) -> &string: &local.name # error: local-reference-escapes
f(u).len()#Captures
This section defines what a closure captures and how it may use its captures.
- fn.capture.localsA closure captures local bindings that it references from enclosing lexical scopes.
- fn.capture.no-providersA closure captures no provider from an enclosing
$.withscope: each requirement key its body uses goes into its row (req.row.omitted.outer-scope). - fn.capture.provider-valueA provider value bound to a local by
$.useis captured like any other local, and stays bound after its provider scope ends.
trait Clock:
fn now(self) -> i32
fn make_reader() -> fn() -> i32 $ Clock:
let clock: *dyn Clock = $.use(Clock)
fn() -> i32: clock.now()See also: Lexical And Dynamic Providers.
#Copied And Shared Captures
A closure copies the immutable bindings it captures and shares the variables it captures:
struct Point:
x: i32
y: i32
fn demo() -> i32:
fixed := Point { x: 1, y: 2 }
let mut moving = Point { x: 1, y: 2 }
read_fixed := fn() -> i32: fixed.x
shift := fn() -> void: moving.x = moving.x + 10
shift()
read_fixed() + moving.x- fn.capture.copy.using-splitA captured immutable binding is copied into the closure when the closure is created. The immutable bindings are
:=,using, andusing!bindings and the parameters that are notmut. - fn.capture.copy.valueThe copy is the one
copy := bindingmakes: a struct or a collection becomes the closure's own value, and a reference stays a reference to the same place. - fn.capture.copy.shadowA binding in an inner scope that reuses the captured name is a new binding. The closure keeps the one it captured.
- fn.capture.cellA captured variable is shared with its scope through a cell. The variables are
letandlet mutbindings,mutparameters, and the bindings of afor,match, orletpattern. - fn.capture.cell.writesEach side sees the other's writes: assignments, in-place field writes, and collection changes such as
p.x = 1andxs.push(1). - fn.capture.cell.freshEach run of a variable's declaration makes a new cell. A closure shares the cell that existed when the closure was created.
- fn.capture.cell.closuresClosures that capture one variable share its cell with each other.
- fn.capture.copiesCopying a closure value copies no cell: the copies share every cell the closure captured.
- fn.capture.call.anyA closure may be called any number of times, through any copy of it.
- fn.capture.referenceCapturing a counted reference copies the reference, as
ref.capture.copystates. - fn.capture.local-parameterA closure supplied directly for a
fn(A) -> R $ Rowparameter may capture local references because that parameter has a fresh lifetime. - fn.capture.local-originsThe supplied closure value carries the origins of its captured local references.
- fn.capture.local-usesThe callee may call that parameter, pass it to another direct function parameter, or return it as a dependent result.
- fn.capture.local-storeStoring that parameter in a field, a box, a provider, or a top-level binding is an error. Error:
local-reference-escapes. - fn.capture.local-fieldA closure written for a struct field of a type parameter may capture local references, as
ref.generic.outlives.fieldstates. - fn.capture.local-genericA closure written as a call argument for a bare type parameter may capture local references, as
ref.generic.outlives.argumentstates. - fn.capture.no-local-reference-storedA closure in any other function-value position must not capture a local reference, as
ref.local.escape.capture-storedstates. Error:local-reference-escapes.
Why. An immutable binding never changes, so copying it and sharing it look the same. A variable changes, so the closure and its scope must refer to one place, as Go, Swift, and Kotlin closures do.
See also: Loops.
#Plain Closures
Every closure is a plain fn closure, and it may mutate through its
captures:
struct User:
name: string
fn rename(user: &mut User) -> void:
user.name = "renamed"
fn plain_closure(user: *mut User) -> fn() -> void:
fn() -> void:
rename(user)
fn make_appender(items: *mut List[i32]) -> fn(i32) -> void:
fn(value: i32) -> void:
items.push(value)- fn.capture.accessA closure uses each capture with the access that the captured binding has in the enclosing scope.
- fn.capture.mutateA closure may assign captured
letstorage, change a capturedlet mutbinding in place, and write through a captured*mut Treference. - fn.capture.mutate.formsCalling a
&mut selfmethod on a capturedlet mutlist or through a captured*mut Treference is such a use. So are passing a captured*mut Treference to a&mut Tparameter, and returning it. - fn.capture.readonlyA read-only capture stays read-only. Assigning a field through a captured
*Treference is an error. Error:not-writable. - fn.capture.result-not-weakenedA callable's declared
*mut Tresult is not weakened when the callable is read through a read-only reference.
struct User:
name: string
fn rename(user: *User) -> void:
change := fn() -> void:
user.name = "Grace" # error: not-writable
change()#Mutable Closures
A closure that mutates captured state is an ordinary closure with an ordinary function type:
let count = +0
let next: fn() -> i32 = fn() -> i32:
count = count + 1
count- fn.capture.no-mut-formThere is no mutable closure type or literal. A closure that mutates captured state has an ordinary
fn(...) -> Ttype. - fn.capture.storage.lifetimeIf a closure outlives the original stack activation, the runtime preserves its captured storage through garbage collection.
Why. hd has no unique borrows, so a mutation capability on function types would protect nothing. Swift, Kotlin, and Go closures also mutate their captures freely.
#Scope Of This Section
- fn.capture.in-processThis section defines ordinary in-process closure behavior only.
- fn.capture.serializable-deferredSerializable closure capture, how a restored closure names its code beyond the same compiled program, and restoration semantics are deferred to the runtime design.
fn apply_twice(f: fn(i32) -> i32, x: i32) -> i32:
f(f(x))
fn demo() -> i32:
apply_twice(fn(n) -> i32: n + 1, 10)#Multiple Inline Closures
Multiple multiline closures may be passed by parenthesizing each closure expression and separating the arguments with commas:
choice(
(
fn(a):
println(a)
),
(
fn(b):
println(b)
),
)- fn.multi.parenthesizedMultiple multiline closures may be passed by parenthesizing each closure expression and separating the arguments with commas.
- fn.multi.commasNewlines do not replace commas in argument lists.
- fn.multi.unparenthesizedWithout parentheses, the line after an indented closure body must start with
,or a closing delimiter. It must be indented no farther than the line holding the closure header. - fn.multi.next-closureThe next closure may start on that line, as in
, fn(b):. - fn.multi.syntax-errorA later argument written at body indentation, or a closing delimiter at the end of a body line, is a
syntax-error.
Why. Parentheses make each multiline closure's boundary explicit.
See also: Physical And Logical Lines.
#Trailing Callback Blocks
When the final parameter has a zero-argument function type, a call may supply it as an indented trailing block:
result := when(a, b):
compute_result()
transaction:
save_user()- fn.trailing.formWhen the final parameter has a zero-argument function type, a call may supply it as an indented trailing block.
- fn.trailing.argumentsOrdinary arguments remain in parentheses.
- fn.trailing.empty-parenthesesIf there are no ordinary arguments, empty
()is omitted. - fn.trailing.closureThe trailing block is equivalent to a zero-argument closure whose result and behavior are contextually inferred from the final parameter.
- fn.trailing.positionA trailing block call may be a complete statement or the complete right-hand side of
:=,let ... =,=,_ :=,return, orbreak. Examples aretotal = sum_of(items):andreturn retry(3):, each followed by the block. - fn.trailing.oneOnly one trailing block is permitted, and only for a zero-argument final parameter. Error:
trailing-block-position. - fn.trailing.parameterizedParameterized callbacks use explicit closure syntax.
- fn.trailing.return
returninside the block returns from the generated callback, not from the enclosing function. - fn.trailing.suspendingWhen the final parameter has a suspending function type, as in
body: fn!() -> T, the trailing block is a suspending closure. This holds for every callee. - fn.trailing.suspending.bodySuch a block is a suspending body, so it may make bang calls.
- fn.trailing.fn-boundA final parameter whose type is a bare type parameter
Fwith a zero-argument boundF < Fn() -> TorF < FnMut() -> Ttakes a trailing block as a function type does. The block is a closure checked against that bound, so underFnit changes no capture byfn.trait.read-only.
fn transaction(body: fn() -> void) -> void:
body()
fn save_user() -> void:
return
transaction:
save_user()
: # error: trailing-block-position
save_again()A trailing block for an fn! parameter may make bang calls:
fn fetch_count!() -> i32: 3
fn twice!(body: fn!() -> i32) -> i32:
body!() + body!()
fn total!() -> i32:
count := twice!():
fetch_count!()
countWhy. The
!in the callee's parameter type marks the block as suspending, as a Kotlinsuspendfunction-type parameter does for its trailing lambda.
#Generic Functions
Generic parameters follow the function name:
fn first[T](items: List[T]) -> T?:
...Trait bounds compose with &:
fn audit[T < Display & Named](value: T) -> string:
...Callers may rely on inference or write an explicit type argument list:
first(names)
first::[string](names)- fn.generic.parametersGeneric parameters follow the function name.
- fn.generic.bounds-andTrait bounds compose with
&. - fn.generic.call-listCallers may rely on inference or write an explicit type argument list, which may omit trailing slots.
- fn.generic.call-markerIn an expression, the explicit list follows
::, as infirst::[string](names), while a type keepsList[string]. - fn.generic.erasedGeneric parameters are erased.
#Explicit Type Arguments
- fn.generic.explicit.trailingAn explicit type-argument list may omit trailing slots. Each omitted slot is inferred as a
_slot is, then takes its default if inference leaves it unsolved. - fn.generic.explicit.too-long-countA list with more slots than the function has generic parameters is an error. Error:
argument-count. - fn.generic.explicit.row-dollarThe slot of a row parameter takes a row type argument, written after
$even for one key or a row alias. Examples are::[$ Log],::[$ AppRow], and::[$()]. A bare key or row alias there is an error. Error:generic-kind-mismatch.
fn pair[Left, Right](left: Left, right: Right) -> (Left, Right):
(left, right)
value := pair::[string]("left", 1) # Right is inferred as usize, the fallbackfn pair[Left, Right](left: Left, right: Right) -> (Left, Right):
(left, right)
fn triple() -> (string, i32):
pair::[string, i32, bool]("left", 1) # error: argument-countWhy. A list names only the leading arguments the reader should see or inference cannot find, as C++ deduces trailing template arguments. The rest are inferred, or take their defaults.
An explicit list may write _ in any slot to infer that argument:
fn convert[From, To](value: From) -> To:
...
user := convert::[_, User](payload)- fn.generic.placeholderAn explicit list may write
_in any slot to infer that argument. - fn.generic.placeholder.solveA placeholder is solved from call arguments, the expected result type, and the function's generic constraints.
- fn.generic.placeholder.defaultWhen those constraints do not determine one type, the parameter's default applies.
- fn.generic.placeholder.unsolvedA placeholder that neither the constraints nor a default determine is an error. Error:
cannot-infer-type. - fn.generic.placeholder.not-type
_is an inference instruction, not a type: in a body it may appear at any depth of an explicit list or aletannotation, ascollect::[List[_]]()does (types.generic.placeholder.local), and never in a declaration.
fn make[T]() -> T:
panic("not implemented")
value := make::[_]() # error: cannot-infer-type#Generic Methods And Qualified Calls
The same explicit-list rules apply to generic methods:
parser.parse::[User](text)
parser.convert::[_, User](payload)- fn.generic.methodsThe same explicit-list rules apply to generic methods.
- fn.generic.qualifiedThey also apply to qualified calls of generic associated functions and trait methods.
- fn.generic.qualified.member-listThe method-level list follows the member name, as in
Type::name::[T](...)andTrait::name::[T](receiver, ...). - fn.generic.qualified.owner-listType arguments of the qualifying type or trait stay before the member's
::, as inAdd::[Money]::add(left, right). - fn.generic.bangA bang call keeps the
!on the name, as the declaration does, and writes the list after it. - fn.generic.bang.examples
fn fetchis called asfetch!::[User](key), and suspending methods asparser.load!::[User](text)andStore::load!::[User](key). - fn.generic.method-inferenceA generic method may still rely entirely on inference by omitting the list.
- fn.generic.dot-member-valueA dot member with type arguments and no call, as in
parser.parse::[User], is not a function value; the reference form isparser::parse::[User].
#Methods And Receivers
Functions declared in impl blocks are methods when their first parameter
is a receiver: self, mut self, &self, &mut self, *self, or *mut self:
impl User:
fn domain(self) -> string:
self.email.slice(1, self.email.len())
fn tagged[T](self, value: T) -> T:
value
label := user.tagged::[string]("admin")- fn.method.receiver-formsA function declared in an
implblock is a method when its first parameter is a receiver, in one of the forms of the table below. - fn.method.no-long-formA receiver has no long form, so
self: &mut Selfis an error. Error:syntax-error. - fn.method.mut-self-structOn a struct, a list or a map,
mut selfis the method's own changeable copy of the receiver, amutparameter namedself. The caller's value is unchanged unless the method returns the copy and the caller keeps it. - fn.method.no-ownership-receiverThere is no ownership-taking receiver form.
- fn.method.associatedReceiverless members are associated functions and are called with qualified
Type::function(...)orTrait::function(...)syntax. - fn.method.eval-orderMethod-call syntax evaluates the receiver first and then ordinary arguments.
- fn.method.equivalenceIt is semantically equivalent to selecting the resolved method and supplying the receiver as its first argument.
- fn.method.value-deferredThe treatment of bare
receiver.methodas a function value is deferred.
| Receiver | Type of self |
What the method gets |
|---|---|---|
fn.method.receiver.selfself |
Self |
the method's own copy of the receiver, which never changes |
fn.method.receiver.mut-selfmut self |
Self |
on a struct, a list or a map, the method's own changeable copy of the receiver |
fn.method.receiver.ref-self&self |
&Self |
a read of the caller's value, with no copy |
fn.method.receiver.ref-mut-self&mut self |
&mut Self |
the caller's value, changed in place |
fn.method.receiver.counted-self*self |
*Self |
a read of the caller's value, which the method may keep |
fn.method.receiver.counted-mut-self*mut self |
*mut Self |
the caller's value, changed in place, which the method may keep |
#Reference Receivers
A &self, &mut self, *self, or *mut self method refers to the
caller's value, and a call takes the receiver's address for it:
struct Vec2:
x: f64
y: f64
impl Vec2:
fn len_squared(&self) -> f64:
self.x * self.x + self.y * self.y
fn shift(&mut self, d: Vec2) -> void:
self.x += d.x
self.y += d.y
fn demo() -> f64:
let mut p = Vec2 { x: 1.0, y: 2.0 }
p.shift(Vec2 { x: 1.0, y: 1.0 }) # (&mut p).shift(..): p is now (2, 3)
p.len_squared() # 13.0- fn.method.ref-selfIn a
&selfmethodselfis a reference&Self, and in a&mut selfmethod&mut Self. Reads and writes through it follow Values And References. - fn.method.ref-self.kindsA method of any type may take
&selfor&mut self: a struct, an enum, or a primitive. - fn.method.ref-self.keep
&selfand&mut selfare local references, so the method must not store or captureself. It may return a value that depends onself, as Dependent Results states. Error:local-reference-escapes. - fn.method.ref-self.local.fixThe diagnostic's fix-it writes
*selffor&self, and*mut selffor&mut self. - fn.method.counted-selfIn a
*selfmethodselfis a counted reference*Self, and in a*mut selfmethod*mut Self. The method may store, return, and capture it. - fn.method.counted-self.kindsA method of any type may take
*selfor*mut self, as for&self. - fn.method.counted-self.referenceA
*selfor*mut selfcall on a counted reference passes that reference on, so the method refers to the same object. - fn.method.counted-self.placeA
*selfor*mut selfcall on a place, such as a local, a parameter, a field, or an element, is an error. Box the value first, as inxs := box([1, 2, 3]). Error:local-reference-escapes. - fn.method.counted-self.temporary-errorA
*selfor*mut selfcall on a non-place temporary is an error too. Box the value first, as inbox(fresh()).handle(). Error:local-reference-escapes. - fn.method.counted-self.local-receiverA
*selfor*mut selfcall through a local reference is an error, since a local reference never converts to a counted one. Error:local-reference-escapes. - fn.method.auto-addressCalling a
&selfor&mut selfmethod on a place takes the place's address.p.shift(d)means(&mut p).shift(d), and no mark appears at the call. - fn.method.auto-address.placeA place is what
&refers to (Places And New Objects): a binding, a struct field of a place, or a value reached through a reference. - fn.method.auto-address.referenceA receiver that is itself a reference is passed on, so through
r: &mut Vec2,r.shift(d)changes whatrrefers to. - fn.method.auto-address.temporaryOn a non-place temporary, a
&selfor&mut selfcall refers to a new object holding its value. - fn.method.auto-address.temporary.callThe receiver temporary is kept alive until the call returns.
- fn.method.auto-address.place-writableWhen a
&mut selfcall addresses a place, that place must be writable. Error:not-writable. - fn.method.auto-address.fixThe fix-it writes
let mutfor aletor:=binding,mutbefore a parameter name, and&mut selffor aselfreceiver. - fn.method.auto-address.shared-referenceA
&mut selfcall through a&Treference is an error. Error:not-writable. - fn.method.auto-address.collection-elementA list element or a map value is a place for the call, as in
bodies[i].shift(d)andteams[name].rename(n), also through a reference to the collection, as inr[i].shift(d). The call takes an element reference (Element References) whose access lasts from before the arguments are evaluated until the call returns. A&mut selfcall needs the collection in a writable place, as&mut xs[i]does. - fn.method.self-struct-writeWriting a field of
selfin a struct'sselfmethod is an error, with a fix-it that takes&mut self. Error:non-reassignable-parameter-binding.
struct Point:
x: i32
y: i32
impl Point:
fn shift(&mut self, dx: i32) -> void:
self.x += dx
fn reset(self) -> void:
self.x = 0 # error: non-reassignable-parameter-binding
fn make() -> Point:
Point { x: 0, y: 0 }
fn demo() -> void:
origin := Point { x: 0, y: 0 }
origin.shift(1) # error: not-writable
let fixed = Point { x: 1, y: 1 }
fixed.shift(1) # error: not-writable
make().shift(1) # a writable temporary, discarded after this callstruct Counter:
hits: i32
impl Counter:
fn handle(*mut self) -> *mut Counter:
self
fn invalid(shared: *mut Counter) -> void:
let mut local = Counter { hits: 0 }
h := local.handle() # error: local-reference-escapes
k := shared.handle() # valid: passes the counted reference onWhy. A method says whether it changes its receiver, and the
let mutbinding says that the value may change, so the call needs no mark, as in Go. A temporary is a fresh writable value, so a chain needs no intermediate binding. Aselfmethod that writes a field would change a copy nobody sees, Go's lost write through a value receiver, so it does not compile. A*selfmethod may keepself, so its receiver must already be a box: every counted reference then starts at an object.
See also: Member Resolution, which defines member lookup, including promotion; Traits, which defines dynamic dispatch; Member Access.
#Recursion
This section defines recursive functions and closures.
- fn.recursion.named-cycleNamed functions may call themselves or other visible named functions recursively, provided at least one function in each recursive cycle has a declared result type. The others may omit theirs.
- fn.recursion.closure.no-self-nameClosures do not acquire an implicit self-name.
- fn.recursion.closure.bindingA closure directly initialized by a statement-form local
:=orletbinding may refer to that binding's name inside its body. - fn.recursion.closure.resultIts result type after
->is mandatory. - fn.recursion.closure.parametersParameter types may be supplied by an expected function type or written on the closure.
- fn.recursion.closure.checkThe compiler checks recursive calls against that established function type, not against a result inferred from the recursive body.
- fn.recursion.closure.outerOrdinary references in the initializer outside the closure body still resolve in the outer scope.
- fn.recursion.closure.ordinary-bindingThe self-reference uses the ordinary binding.
- fn.recursion.closure.letWith
let, reassignment changes which function a later recursive call invokes. - fn.recursion.closure.initializedA closure body cannot execute until its binding's initializer completes.
- fn.recursion.closure.no-forwardThis exception does not enable general forward references or mutual recursion between local closures.
fn sum_to(limit: i32) -> i32:
sum := fn(n: i32): # error: recursive-function-needs-result-type
if n == 0: 0
else: n + sum(n - 1)
sum(limit)See also: Declarations.
#Program Entry Functions
This section defines program entry functions.
- fn.entry.main
pub fn main() -> voidorpub fn main() -> Result[void, E]is the default non-suspending entry point. - fn.entry.no-parametersIt has no source-level parameters.
- fn.entry.suspendingA suspending entry point is named
main!. - fn.entry.requirementsEntry points may declare host requirements with the ordinary
$clause. - fn.entry.pub
pubcontrols module visibility and does not itself create a Wasm host export.
pub fn main() -> void:
passOpen in playground#Call-Site Locations
A @track_caller function knows where it was called. Two accessors on
std.debug.Location read that call site:
use std.debug.Location
@track_caller
fn check_positive(value: i32) -> void:
if value <= 0:
at := Location::caller()
panic("not positive at ${at.file}:${at.line}:${at.column}")
pub fn main() -> void:
check_positive(3) # a failure would name this lineOpen in playground- fn.caller.decorator
track_calleris a compiler-known prefix decorator. It is not a value, needs no import, and attaches no fact. - fn.caller.targetA bare
@track_callerline precedes only a module-level function. Any other spelling or target is an error. Error:decorator-target-kind. - fn.caller.duplicateA module-level function has at most one
@track_callerline. Error:duplicate-fact. - fn.caller.readsA
@track_callerfunction reads its record when its body callsLocation::caller()orLocation::caller_args(). It reads it too when its body makes a direct call of a@track_callerfunction that reads its record. The closures it contains count as its body. - fn.caller.site-argumentA
@track_callerfunction that reads its record takes one hidden argument after its written ones: a pointer to the call site's record. Each direct call of it passes one. A call of one that does not read its record passes none. The function's type does not show it. - fn.caller.recordA call site's record is static data. It holds the call's location, whether the call site is in the user's own code, and the argument texts when the callee reads them.
- fn.caller.record.argsA record holds argument texts only when its callee calls
Location::caller_args(), directly or through a chain of@track_callerfunctions. - fn.caller.chainInside a
@track_callerfunction, a direct call of another@track_callerfunction passes the outer call's record on. So both accessors describe the outermost call. - fn.caller.valueA
@track_callerfunction used as a value binds the record of the place where the value is created, with no argument texts. A call through a function value passes no hidden argument. - fn.caller.accessor.location
std.debugdeclares@intrinsic pub fn caller() -> LocationonLocation. It returns the location of the call whose record the function received. - fn.caller.locationA
Locationholds the file as diagnostics name it, and the 1-based line and column where the call begins. The column counts characters. - fn.caller.accessor.args
std.debugdeclares@intrinsic pub fn caller_args() -> List[CallArg]onLocation. It returns oneCallArgfor each argument of that call, in order, with its source text,start, andend. - fn.caller.accessor.args.completeThe argument texts are known for a call with no spread and no trailing block, its named arguments included. For any other call, the list is empty.
- fn.caller.accessor.args.nameThe list holds the call's arguments in source order, positional and named. A
CallArg'snameis the parameter name of a named argument, and none for a positional one. Its text and span are the argument's value, without the name. - fn.caller.accessor.args.endA
CallArg'sendis the location just after the argument's last character. - fn.caller.accessor.insideEither accessor is valid only lexically inside a
@track_callerfunction, the closures it contains included. Error:caller-outside-track-caller. - fn.caller.root-package
Location::in_root_package()is true when the call site is in the user's own code, asmodule.dbg.own-codedefines it. It is tested at run time, and no call is compiled out. - fn.caller.framesA panic report's frame list leaves out each frame in the body of a
@track_callerfunction, the closures it contains included. So the list names the caller where the function was called.
use std.debug.Location
fn plain() -> u32:
Location::caller().line # error: caller-outside-track-callerWhy. A helper such as an assertion is most useful when its failure names the line that called it. Rust's
#[track_caller]andLocation::caller()do this with one hidden argument, so a call that never fails pays one pointer and no allocation.A failure inside such a helper is the caller's mistake, so its frame list starts at the call, as Rust's
#[track_caller]reports the caller's location.
#Unsupported Function Extensions
- fn.unsupported.featureshd-lang has no general recursive local binding facility, shorthand-argument closures, or non-local returns from closures.
fn double_all(items: List[i32]) -> List[i32]:
items.map(fn(x: &i32) -> i32: *x * 2) # the closure is written out#Method Values
Method values are written as :: method references.
The rules below still hold:
- fn.unsupported.qualified-callA qualified call such as
User::guest(),Display::to_string(&value), orAdd::[Money]::add(left, right)remains an ordinary call. - fn.unsupported.closure-adapterAn explicit closure, such as
fn(user: User) -> string: user.domain(), adapts a method where a function value is needed. - fn.unsupported.variant-valueA variant constructor with exactly one payload field, written
Enum.Variantwith a.and no argument clause, is already a function value. - fn.unsupported.variant-multiA constructor with two or more payload fields stays an error. Error:
unsaturated-enum-constructor.
struct Counter:
value: i32
impl Counter:
fn read(self) -> i32: self.value
fn demo(counter: Counter) -> i32:
read := counter::read # a bound method value: the receiver is fixed now
read()See also: Enum Declarations.