Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Modules

Each source file is a module. A larger program is several files checked together.

module shop.pricing

pub fn discount(total: i64, percent: i64) -> i64 = total - total * percent / 100

fn round_down(x: i64) -> i64 = x - x % 10
module shop.orders
use shop.pricing

pub struct Order
    id: u64
    total: i64 = 0

pub fn new_order(id: u64) -> Order = Order(id: id)

check new_order(7).total == 0
  • module shop.pricing gives the module its name. Without it, the name comes from the file path.
  • use shop.pricing makes that module visible.
  • pub marks an item other modules may use. Everything else stays private to its module.

Give all the files of a program to rce in one command:

$ rce check shop/pricing.rce shop/orders.rce
ok shop/pricing.rce
ok shop/orders.rce
exit status: 0

Checked alone, orders.rce is refused, because the module it uses is not part of the program:

$ rce check shop/orders.rce
REFUSED shop/orders.rce: line 2: W-NAME-1 unknown module `shop.pricing`
exit status: 1

Calling into another module

A used module is visible by its last name, so shop.checkout calls pricing.discount(...):

module shop.checkout
use shop.pricing

pub fn sale_price(total: i64) -> i64 = pricing.discount(total, 10)

check sale_price(200) == 180
$ rce test shop/pricing.rce shop/checkout.rce
ok shop/pricing.rce (0 examples, 0 checks)
ok shop/checkout.rce (0 examples, 1 checks)
2 passed, 0 failed
exit status: 0

Only pub items can be reached this way. round_down in shop.pricing has no pub, so a call to it from another module is refused:

module shop.rounding
use shop.pricing

fn rounded(total: i64) -> i64 = pricing.round_down(total)
$ rce check ../shop/pricing.rce private_call.rce
ok ../shop/pricing.rce
REFUSED private_call.rce: line 4: W-VIS-1 `round_down` is private to module `shop.pricing`
exit status: 1

The modules std.text, std.collections and std.math are built in and can always be used.

What you learned

  • module, use and pub.
  • All files of a program are checked together.
  • A used module is reached by its last name, and only its pub items are visible.