19. Function values
A function’s name, used without calling it, is a value of type
fn(T, U) R (its parameter and result types). It can be stored, passed,
returned, compared with ==, and called: f(x) for a local or parameter
f, s.f(x) for a field. A generic function is not a value (E103). There
are no closures: what a function needs comes through its parameters.
A parameter’s mode is part of the type: a function taking inout b: Buf(u8)
has type fn(inout Buf(u8)) void, and one taking sink b: Buf(u8) has type
fn(sink Buf(u8)) void. These are different types from fn(Buf(u8)) void,
so a function fits only where its modes are expected (E103). A call through
a function value follows the same rules as a direct call: f(&b) for inout,
and f(b) moves b into a sink parameter. The check takes such a call to
change everything it is given as inout. An extern fn cannot take a function
type with modes (E132), and sink on a type that owns nothing is E145, as
in a function.
// expect: 8
// expect: 15
uses io
const Op = struct {
run: fn(i64, i64) i64
}
fn add(a: i64, b: i64) i64 {
return a + b
}
fn mul(a: i64, b: i64) i64 {
return a * b
}
fn twice(f: fn(i64, i64) i64, x: i64) i64 {
return f(x, x)
}
fn main(io: Io) void {
io.print(twice(add, 4))
const op = Op{ .run = mul }
io.print(op.run(3, 5))
}
For the capability check, taking a function as a value counts as calling
it: the function that takes it uses what it uses. Whoever receives the
value may call it, as whoever receives an Io may print: a module without
uses io can call a printing function it was handed, but cannot make one.