Functions
Basic Functions #
fn greet(name: str) -> str {
"Hello, {name}!"
}
fn add(a: int, b: int) -> int {
a + b // implicit return — last expression is the return value
}
Explicit Return #
fn absolute(x: int) -> int {
if x < 0 {
return -x
}
x
}
No Return Type #
Functions that don't return a value omit the -> Type:
fn say_hello(name: str) {
print("Hello, {name}!")
}
Parameters #
Type Annotations #
fn process(x: int, y: f64, name: str) -> str {
"{name}: {x}, {y}"
}
Named Arguments #
fn create_user(name: str, age: int, email: str) -> User {
User { name, age, email }
}
// Call with named arguments
create_user(name: "Alice", age: 30, email: "alice@example.com")
Default Values #
Parameters can have default values in struct fields and builder patterns.
Lambdas / Closures #
Lambdas use the |params| expr syntax:
// Single expression
let double = |x| x * 2
let add = |a, b| a + b
// With type annotations
let square = |x: int| -> int { x * x }
// Multi-line body
let process = |x: int| -> int {
let y = x * 2
y + 1
}
Closures Capture Variables #
let multiplier = 3
let multiply = |x| x * multiplier // captures `multiplier`
print(multiply(5)) // 15
Higher-Order Functions #
Functions can take functions as parameters and return functions:
fn apply(f: fn(int) -> int, x: int) -> int {
f(x)
}
fn make_adder(n: int) -> fn(int) -> int {
|x| x + n
}
let add5 = make_adder(5)
print(add5(10)) // 15
Methods #
Methods are defined inside impl blocks. See Data Structures for details.
struct Circle {
radius: f64,
}
impl Circle {
fn area(self) -> f64 {
3.14159 * self.radius * self.radius
}
fn new(radius: f64) -> Circle {
Circle { radius }
}
}
let c = Circle { radius: 5.0 }
print(c.area())
Decorators #
Functions can be annotated with decorators:
@test
fn test_addition() {
assert_eq(2 + 2, 4, "basic addition")
}
@memoize
fn fibonacci(n: int) -> int {
if n <= 1 { n } else { fibonacci(n - 1) + fibonacci(n - 2) }
}
@deprecated("use new_function() instead")
fn old_function() {
// ...
}
See Decorators for the full list.