Functions
Declaring Functions
Section titled “Declaring 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
returnneeded). - You can use
returnfor early exits.
Calling Functions
Section titled “Calling Functions”let message = greet("Alice")print(message) // Hello, Alice!Default Parameters
Section titled “Default Parameters”fn connect(host: String, port: Int = 8080) { // ...}
connect("localhost") // port defaults to 8080connect("localhost", 3000) // port is 3000Multiple Return Values
Section titled “Multiple Return Values”Use tuples:
fn divide(a: Int, b: Int) -> (Int, Int) { (a / b, a % b)}
let (quotient, remainder) = divide(17, 5)Closures
Section titled “Closures”Anonymous functions that capture their environment:
let double = |x: Int| -> Int { x * 2 }print(double(5)) // 10
// Type inference works for closures toolet add = |a, b| a + bprint(add(3, 4)) // 7Higher-Order Functions
Section titled “Higher-Order Functions”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) // 25Common Patterns
Section titled “Common Patterns”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) // 15Methods
Section titled “Methods”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.53975Next Steps
Section titled “Next Steps”Learn about control flow — conditionals, loops, and pattern matching.