Skip to content
All guides

learn

Functions

Name the operations so main stays a script of intent.

fn apply(total: int, amount: int) -> int {
    total + amount
}

fn main() {
    tx = [5000, -1200, 300]
    mut total = 0
    for amount in tx {
        total = apply(total, amount)
    }
    println(total)
}
  • Parameters need types
  • Last expression is the return value
  • return expr to leave early
fn apply(total: int, amount: int) -> int {
    if total + amount < 0 {
        return total
    }
    total + amount
}

That still swallows the overdraft silently. We will make failure visible in errors. First, give transactions a shape: structs.