Chapter 4 — Functions
You’ve already met functions; let’s make the relationship official.
fn add(a: int, b: int) -> int {
return a + b
}
fn fib(n: int) -> int {
if n < 2 { return n }
return fib(n - 1) + fib(n - 2) // recursion is welcome
}
fn main() -> int {
return add(fib(10), 1) // => 56
}
The shape is fn name(params) -> ReturnType { body }. A few firm rules:
- Parameter types are mandatory. No inference at the boundary.
- Parameters are immutable. Inside the function, a parameter behaves like a
let— you can read it all you like, but you can’t reassign it. If you want a mutable working copy, make one withvar. - Arguments are checked for count and type, with no coercion. Call
add(fib(10), 1)and Ingle confirms you passed exactly twoints. - Order doesn’t matter.
fibcan call itself, and any function can call any other function defined anywhere in the file. Ingle reads all the signatures first, then checks the bodies, so forward references and mutual recursion Just Work — no forward declarations, no header files.
Functions that return nothing
If you leave off the -> T, you’ve written a unit function — one that runs for its effect
and produces no value:
fn greet(name: string) {
println("Hello, {name}")
return // a bare 'return' is fine; so is just falling off the end
}
fn main() {
greet("Ingle")
}
Inside a unit function, a bare return (with no value) bails out early, and reaching the
closing brace returns nothing at all. What you can’t do is return a value from one
(return 5 in a unit function is an error), and you can’t capture its non-existent result:
let x = greet("Ingle") // error: there's no value here to bind
This is the same principle as the strict bool: Ingle won’t let you pretend a nothing is a
something. main is allowed to be a unit function too — as you saw in Chapter 1, it then
quietly hands back 0.
Fireside trivia. The word “unit” comes from type theory, where the type with exactly one value is called the unit type. A function that “returns nothing” actually returns that single, contentless value — there’s nothing to choose, so there’s nothing to say. “Void” and “unit” are the same idea wearing different hats: one borrowed from C’s bookkeeping, the other from mathematics’ tidy bookkeeping.