Functions
Functions are the bread and butter of any program. Coco's function design focuses on clarity, safety, and zero-cost abstractions.
What's in This Chapter
We'll cover everything about functions:
- Basics — Definition syntax, parameters, and return types
- Parameter Passing — How Coco handles ownership and borrowing automatically
- Error Returns — Error unions, auto-propagation, and the catch keyword
- Generics — Generic functions and monomorphization
- Closures — Lambdas, capturing, and higher-order functions
Design Philosophy
Coco's approach to functions is guided by a few key principles:
Clear signatures. You should be able to look at a function signature and understand what it does, what it needs, and what can go wrong.
No hidden costs. If a function can fail, you'll see it in the return type. If it takes ownership of a parameter, that's explicit.
Zero-cost abstractions. Generics compile to monomorphized code—as fast as if you wrote specialized versions by hand.
Automatic safety. The compiler handles parameter passing modes and error propagation so you don't have to think about it constantly.
Quick Examples
// Basic function
fn greet($name string) {
echo "Hello, {}!", $name;
}
// With return type
fn add($a i32, $b i32): i32 {
return $a + $b;
}
// Can fail (error union)
fn read_file($path string): !string {
if !file_exists($path) {
return error("File not found: {}", $path);
}
return fs::read($path);
}
// Generic function
fn swap<T>($a &T, $b &T) {
$temp = *$a;
$a = $b;
*$b = $temp;
}
// Closure
$doubled = $numbers.iter().map(($x) { $x * 2 }).collect();
Let's explore each of these concepts in detail.
Pages in this chapter:
- Function Basics — Function definitions, parameters, and return types in Coco
- Parameter Passing — How Coco automatically handles value vs reference passing
- Error Returns — Error unions, auto-propagation, and graceful error handling
- Generics — Generic functions, type parameters, and monomorphization
- Closures — Lambdas, capturing, and higher-order functions