Skip to content

Functions

fn greet(name: String) -> String {
"Hello, " + name + "!"
}
  • Parameters are name: Type.
  • Return type follows ->.
  • The last expression in the body is the return value (no return needed).
  • You can use return for early exits.
let message = greet("Alice")
print(message) // Hello, Alice!
fn connect(host: String, port: Int = 8080) {
// ...
}
connect("localhost") // port defaults to 8080
connect("localhost", 3000) // port is 3000

Use tuples:

fn divide(a: Int, b: Int) -> (Int, Int) {
(a / b, a % b)
}
let (quotient, remainder) = divide(17, 5)

Anonymous functions that capture their environment:

let double = |x: Int| -> Int { x * 2 }
print(double(5)) // 10
// Type inference works for closures too
let add = |a, b| a + b
print(add(3, 4)) // 7

Functions that take or return other functions:

fn apply(f: |Int| -> Int, value: Int) -> Int {
f(value)
}
let result = apply(|x| x * x, 5)
print(result) // 25
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map(|x| x * 2) // [2, 4, 6, 8, 10]
let evens = numbers.filter(|x| x % 2 == 0) // [2, 4]
let sum = numbers.reduce(0, |acc, x| acc + x) // 15

Define methods on structs using impl:

struct Circle {
radius: Float,
}
impl Circle {
fn area(self) -> Float {
3.14159 * self.radius * self.radius
}
fn scale(mut self, factor: Float) {
self.radius = self.radius * factor
}
}
let c = Circle { radius: 5.0 }
print(c.area()) // 78.53975

Learn about control flow — conditionals, loops, and pattern matching.