Skip to content

Functions

A function lists its parameter types and its return type. Parameters that are only read are usually borrowed with &, so the caller keeps the value.

fn area(width: f64, height: f64) -> f64 {
return width * height
}
fn shout(text: &Str) -> Str {
return text.to_upper() + "!"
}
let title = "hello"
print(f"{area(2.0, 3.5)}")
print(shout(&title))
print(title)
7.0
HELLO!
hello

Every function says return. There is no implicit last-expression return, so a reader never has to guess which line is the result.

A closure is written fn(x) => expression, or with a block. A closure that uses variables from around it lists them in brackets, so what it captures is visible at a glance.

let numbers = [3, 8, 1, 9]
let doubled = numbers.map(fn(n) => *n * 2)
let limit = 5
let big = numbers.filter(fn(n: &i64) -> bool [limit] => *n > limit)
print(f"{doubled.len()} {big.len()}")
4 2

Type parameters go in angle brackets. A bound such as T: Order says what the function needs from the type; numbers and Str already have Order.

fn largest<T: Order>(items: &Vec<T>) -> i64 {
let mut best = 0
for i in 1..items.len() {
if items[i] > items[best] {
best = i
}
}
return best
}
let scores = [12, 40, 7]
let names = ["kiwi", "apple", "pear"]
print(f"{largest(&scores)} {largest(&names)}")
1 2