Skip to content
All guides

learn

Structs

Loose integers were fine for a page. A real ledger has accounts and transactions.

struct Tx {
    amount: int
    note: text
}

struct Account {
    owner: text
    balance: int
}

fn main() {
    a = Account { owner: "Ada", balance: 0 }
    t = Tx { amount: 5000, note: "payroll" }
}

Field access: a.owner, t.amount.

No inheritance. Compose structs. Put methods on the type when the operation belongs to it:

struct Account {
    owner: text
    balance: int

    fn credit(mut self, amount: int) {
        self.balance = self.balance + amount
    }
}

mut self exclusive. Most day-to-day code never writes ref: the compiler inserts borrows for you.

Enums (tagged unions) come next when a transaction can be deposit *or* withdrawal as a variant. For the CLI, a signed amount is enough.

Next: errors.