Skip to content

Functions and lambdas

fn double(x: int) -> int {
return x * 2
}
fn main(caps: Caps) -> int {
return double(21)
}

Return type is required on functions. Function bodies need an explicit return (trailing bare expressions are for block/match arms, not whole functions).

fn double(x: int) -> int {
return x * 2
}
fn is_even(x: int) -> bool {
return x % 2 == 0
}
fn main(caps: Caps) -> int {
let xs = [1, 2, 3, 4]
let ys = array_map(xs, double)
let evens = array_filter(xs, is_even)
print ys
print evens
return len(evens)
}

Paren lambdas only — not |x| …:

fn main(caps: Caps) -> int {
let xs = [1, 2, 3, 4]
let zs = array_map(xs, (x: int) -> x * 3)
let evens = array_filter(xs, (x) -> x % 2 == 0)
print zs
print evens
return 0
}
Form Status
(x: int) -> expr Works
(x) -> expr Works (types inferred where possible)
|x| expr Rejected — use paren form

Receiver is an explicit self parameter:

struct User {
name: String
fn greet(self) -> String {
return "hello " + self.name
}
}
fn main(caps: Caps) -> int {
let u = User { name: "Ada" }
print u.greet()
return 0
}

Methods use fn, not function.

type Score = int
fn bump(s: Score) -> Score {
return s + 1
}