---
title: "11.2 pub and import"
url: https://una-lang.org/en/learn/packages/pub-and-import/
release: v0.4.0
edition: "0.2"
---

# 11.2 pub and import

## 11.2.1 What `pub` and `import` do

[Section 6.3](https://una-lang.org/en/learn/functions/what-a-header-says-pub-private-functions-and-inferred-headers/#s6-3) compared a module to a shop: its public functions are the counter, where anyone may ask, and its private ones the back room. Until now every program was one module, so the counter had no other customers. With several modules, it does:

- **`pub`**, short for public, makes a declaration visible to the other modules of the package.
- A declaration without `pub` is **private**: only its own module can use it, as before.
- A module's **interface** is the set of its `pub` declarations: what the rest of the package may rely on.
- An **import** is a line at the top of a module that takes declarations of another module by name, so the module can use them as if they were its own. `import store.money (format)` takes `format` from `store.money`.

A module sees exactly three sources of names: its own declarations, the names it imports, and the **prelude**, the functions and types that every module sees without importing, such as `List`, `Option` and `Console`.

## 11.2.2 Why a module keeps its helpers private

A helper is often written for one job, and assumes things that its module guarantees. Here is the money code again, in one module. `format` handles a negative amount, a refund, by putting the minus sign in front and passing the amount without its sign to `digits`. `digits` was written for amounts of 0 or more. Nothing stops `main` from calling it directly:

```una include="steps/06-helper/src/store.una" title="steps/06-helper/src/store.una" verified="check, run"
module store

--- An amount in cents as a person reads it: 1990 is "19.90", and -150 is "-1.50".
format(cents: Int) -> Text = if cents < 0 then "-{digits(0 - cents)}" else digits(cents)

--- The digits of an amount of 0 or more, with two after the point.
digits(cents: Int) -> Text
=
  let rest = cents mod 100
  if rest < 10 then "{cents / 100}.0{rest}" else "{cents / 100}.{rest}"

pub main() -> Unit
  uses @console: Console[print]
=
  @console.print("a refund of 150 cents, by format: {format(-150)}")
  @console.print("the same refund, by digits: {digits(-150)}")
```

`una run .` prints:

```text include="steps/06-helper/expected/output.txt"
a refund of 150 cents, by format: -1.50
the same refund, by digits: -2.50
```

The second line is wrong: a refund of 150 cents is 1.50, not 2.50. `digits` divides with Una's division, which rounds down, toward the smaller number: -150 / 100 is -2, and the remainder is 50 ([section 2.2](https://una-lang.org/en/learn/numbers/whole-numbers-int/#s2-2) shows why). That is right for the job `digits` was written for, and wrong for any other. The checker cannot know which job a function was meant for.

When `digits` is private to `store.money`, no other module can call it, so it can only be reached through `format`, which keeps its assumption. The module can also change `digits`, rename it or delete it, and no code outside it breaks. [Private stays private](#private-stays-private) shows what happens when another module tries.

## 11.2.3 How to write `pub`

Write `pub` at the very start of the declaration, before its name:

```una include="steps/07-imports/src/store/money.una#format" title="steps/07-imports/src/store/money.una"
--- An amount in cents as a person reads it: 1990 is "19.90", and -150 is "-1.50".
pub format(cents: Int) -> Text = if cents < 0 then "-{digits(0 - cents)}" else digits(cents)
```

`pub` goes on a function, a kind or a predicate, and on two declarations of later chapters: a capability and a handler ([chapter 12](https://una-lang.org/en/learn/capabilities/)), and a policy ([chapter 17](https://una-lang.org/en/learn/information-flow/)). An `example` or a `requirement` is never `pub`: an example belongs to its module, as [Examples of private functions](https://una-lang.org/en/learn/packages/testing-it/#examples-of-private-functions) shows.

A `pub` function promises its callers a header they can rely on, so it writes every clause: its `uses` and its `fails`. A private function may leave them to inference ([section 6.3](https://una-lang.org/en/learn/functions/what-a-header-says-pub-private-functions-and-inferred-headers/#s6-3), [section 7.2](https://una-lang.org/en/learn/failure/declaring-a-failure-fails-and-fail/#s7-2)), since all its callers are in its own module. Give every `pub` declaration a doc comment (`---`), since other modules read it to learn what the declaration does.

## 11.2.4 How to write an import

An import line has four parts:

:::steps
```una include="steps/07-imports/src/store/app.una#L3-L4" title="steps/07-imports/src/store/app.una"
import store.catalog (Product, find)
import store.money (format)
```

1. **`import`.** The keyword that starts the line.
2. **`store.catalog`.** The module path of a module of the same package, or of a standard module.
3. **`(Product, find)`.** In parentheses, each declaration the line takes, by its name, separated by commas. At least one name, and each name once.
4. **`import store.money (format)`.** One line per module: a module that takes names from two modules has two import lines. They come right after the `module` line, before any declaration, sorted by module path, with the names inside each sorted too, names with a capital letter first: `una fmt .` keeps them in that order.
:::

There is no form that imports every name of a module, and no form that imports a module without naming what it takes. A reader of the import lines knows exactly which names come from where.

### 11.2.4.1 Functions

An imported function is used by its plain name, `format(1990)` or `find(catalog, sku)`, as if the importing module had declared it. The same holds for an imported predicate ([section 5.3](https://una-lang.org/en/learn/contracts/refined-kinds-and-predicates/#s5-3)).

### 11.2.4.2 Record kinds, with their constructor and fields

Importing a record kind brings its type, its constructor and its fields. This step's catalog module shares a record, `Product`, and a function that looks a product up, both `pub`:

:::steps
```una include="steps/07-imports/src/store/catalog.una" title="steps/07-imports/src/store/catalog.una" verified="check"
module store.catalog

import store.money (Cents)

--- A product the store sells.
pub kind Product
  sku: Text
  name: Text
  cents: Cents

--- The product with a SKU in a catalog, or `None` for a SKU the catalog does not list.
pub find(catalog: List[Product], sku: Text) -> Option[Product] = catalog.first_where(keep: fn(product) -> product.sku == sku)
```

1. **`import store.money (Cents)`.** A module imports what it uses, even another module's kinds. `Cents`, an `Int` that is never below zero, is a refined kind of [section 5.3](https://una-lang.org/en/learn/contracts/refined-kinds-and-predicates/#s5-3). `Product.cents` is a `Cents`, so a negative price cannot be built anywhere in the package.
2. **`pub kind Product`.** The record, its constructor and its fields are part of the interface. A module that imports `Product` can write `Product(sku: …, name: …, cents: …)` and read `product.name`.
3. **`pub find(...)`.** The lookup: the first product of the list whose SKU matches, found with `first_where` ([section 10.3](https://una-lang.org/en/learn/collections/functions-over-lists-map-filter-and-fold/#s10-3)), or `None` ([section 7.1](https://una-lang.org/en/learn/failure/a-value-that-may-be-missing-option/#s7-1)). The catalog is a parameter, so each caller passes the list of products it works with.
:::

A capability and a handler, which [chapter 12](https://una-lang.org/en/learn/capabilities/) teaches, are shared and imported in the same way: `pub` on the declaration, and the name in an import.

### 11.2.4.3 Sum kinds, with their variants

Importing a sum kind brings its variants with it, so the importing module can build them. This step has a module that tells whether a shelf can sell a SKU:

```una include="steps/08-import-forms/src/store/stock.una" title="steps/08-import-forms/src/store/stock.una" verified="check"
module store.stock

--- Whether a shelf can sell a SKU now.
pub kind Availability = InStock(units: Int) | SoldOut

--- The availability of a shelf that holds `units` units.
pub availability(units: Int) -> Availability = if units > 0 then InStock(units: units) else SoldOut
```

The app imports `Availability`, and with it `InStock` and `SoldOut`:

```una include="steps/08-import-forms/src/store/app.una" title="steps/08-import-forms/src/store/app.una" verified="check, run"
module store.app

import std.host (Console)
import store.stock (Availability, availability)

--- What a shelf card says.
card(sku: Text, stock: Availability) -> Text
=
  when stock
    is InStock(units) -> "{sku}: {units} in stock"
    is SoldOut -> "{sku}: sold out"

--- Prints the card of each shelf.
report(cards: List[Text]) -> Unit
  uses @console: Console[print]
=
  for line in cards
    @console.print(line)

pub main() -> Unit
  uses @console: Console[print]
=
  let lamp = card("LAMP-01", stock: availability(4))
  let desk = card("DESK-02", stock: availability(0))
  let chair = card("CHAIR-09", stock: SoldOut)
  report([lamp, desk, chair])
```

```text include="steps/08-import-forms/expected/output.txt"
LAMP-01: 4 in stock
DESK-02: sold out
CHAIR-09: sold out
```

`card` writes the kind in a parameter's type, and `main` builds a variant, `SoldOut`, so both need the import. A `when` needs no import to match a variant, even in a module that did not import the kind: its arms take the variants of the value's type, whatever module declared it.

### 11.2.4.4 The host's capabilities: `std.host`

The same step also writes `import std.host (Console)`. `std.host` is one of the two standard modules a package can import. It holds the host's capabilities, such as `Console` and `Clock` ([chapter 12](https://una-lang.org/en/learn/capabilities/the-hosts-capabilities-and-grants/#s12-2)), which the prelude already puts in every module. So the import changes nothing but makes the source explicit, and you may leave it out. The other standard module, `std.testing`, holds helpers for examples.

## 11.2.5 A private helper next to a public function

Back to money, now split into modules. `store.money` keeps the helper, `digits`, next to its public `format`:

```una include="steps/07-imports/src/store/money.una" title="steps/07-imports/src/store/money.una" verified="check"
module store.money

--- An amount of money in cents, never below zero.
pub kind Cents = Int where it >= 0

--- An amount in cents as a person reads it: 1990 is "19.90", and -150 is "-1.50".
pub format(cents: Int) -> Text = if cents < 0 then "-{digits(0 - cents)}" else digits(cents)

--- The digits of an amount of 0 or more, with two after the point.
digits(cents: Int) -> Text
=
  let rest = cents mod 100
  if rest < 10 then "{cents / 100}.0{rest}" else "{cents / 100}.{rest}"
```

The app takes what it needs from the two modules, one name at a time:

```una include="steps/07-imports/src/store/app.una" title="steps/07-imports/src/store/app.una" verified="check, run"
module store.app

import store.catalog (Product, find)
import store.money (format)

--- Why a price could not be shown.
kind PriceError = | NotListed(sku: Text)

--- The price of a SKU in a catalog, as a person reads it.
price_tag(sku: Text, catalog: List[Product]) -> Text
  fails PriceError
=
  let product = find(catalog, sku)
    if none fail NotListed(sku)
  "{product.name}: {format(product.cents)}"

pub main() -> Unit
  uses @console: Console[print]
=
  let catalog = [Product(sku: "LAMP-01", name: "Desk lamp", cents: 1990)]
  let lamp = attempt price_tag("LAMP-01", catalog)
  let chair = attempt price_tag("CHAIR-09", catalog)
  @console.print("{lamp}")
  @console.print("{chair}")
```

```text include="steps/07-imports/expected/output.txt"
Ok("Desk lamp: 19.90")
Err(NotListed("CHAIR-09"))
```

`PriceError` and `price_tag` have no `pub`, so they belong to `store.app` alone. A private function may leave its `fails` to inference, but `price_tag` writes it, so its header can be read without its body. `price_tag` calls `find` and `format` by their plain names, since the import lines name them. It also writes `Product` in a parameter's type, `List[Product]`, and `main` builds one, so `Product` is imported too. `attempt` keeps each lookup's outcome as a `Result` ([section 7.4](https://una-lang.org/en/learn/failure/failures-as-values-attempt-and-result/#s7-4)), and the two lines print them: the lamp's text, and the failure for a SKU the catalog does not list.

## 11.2.6 How names are found

### 11.2.6.1 Where a name comes from

When a module uses a name, una looks for it in this order, and the first place that has it wins:

1. the local names: parameters, `let` bindings and the like;
2. the module's own declarations;
3. the names it imports, and the variants of the sum kinds it imports;
4. the prelude.

A name found nowhere is U1001, "cannot find name … in this module, its imports or the prelude". [Using a name you did not import](https://una-lang.org/en/learn/packages/common-mistakes/#using-a-name-you-did-not-import-u1001) shows it. An import of a module that the package does not have, or of a name that the module does not declare, is U1001 too.

### 11.2.6.2 Private stays private

Try to import `digits` into the app:

```diff include="steps/07-imports..steps/09-private:src/store/app.una" context="0" title="src/store/app.una"
--- a/src/store/app.una
+++ b/src/store/app.una
@@ -4 +4 @@
-import store.money (format)
+import store.money (digits, format)
```

`una check .` reports:

```text include="steps/09-private/expected/rendered.txt"
[U1004] Error: function `digits` is private to module `store.money`
    ╭─[ src/store/app.una:4:21 ]
    │
  4 │ import store.money (digits, format)
    │                     ───┬──
    │                        ╰──── function `digits` is private to module `store.money`
    │
    ├─[ src/store/money.una:10:1 ]
    │
 10 │ digits(cents: Int) -> Text
    │ ───┬──
    │    ╰──── declared here without `pub`
    │
    │ Help: repair 1 (widens visibility: every module may then call it: check that it belongs to the module's interface): declare `digits` with `pub`; edit src/store/money.una:10:1..10:1 to "pub "
    │
    │ Note: run `una explain U1004` for an explanation
────╯
```

Read it from the top. The first line names the problem and the module that owns the function. The first mark points at the name in the import, and the second at the declaration in `store.money`, "declared here without `pub`". The help line offers the repair, adding `pub`, but marks it as one that **widens visibility**: every module may then call it. `una fix .` does not apply such a repair by itself. Making a helper public is a decision about the module's interface, and you take it by editing the declaration, with a doc comment for its new callers.

### 11.2.6.3 One name, one meaning

An import and a declaration of the same module share one set of names, so a module cannot declare a name it also imports, and cannot import one name from two modules. Both are U1002, as two declarations of one name are ([An import that clashes with a declaration](https://una-lang.org/en/learn/packages/common-mistakes/#an-import-that-clashes-with-a-declaration-u1002)). A declaration or an import may reuse a name of the prelude: the module's own wins.

### 11.2.6.4 No cycles

If `store.money` imports `store.pricing`, then `store.pricing` cannot import `store.money`, directly or through other modules. A loop of imports is an **import cycle**, U1003 ([An import cycle](https://una-lang.org/en/learn/packages/common-mistakes/#an-import-cycle-u1003)). Without cycles, every module can be read, and checked, after the modules it uses.

## 11.2.7 Choosing what to share and what to import

:::decide
**Which to use:**

| You want… | Use |
| --- | --- |
| A function, kind or predicate that other modules need | `pub`, with a doc comment, and every clause of its header written |
| A helper that only this module uses | no `pub`: it stays private, and may infer its `uses` and `fails` |
| A declaration of another module | `import module.path (name, …)`, one name per declaration |
| A host capability's name, written explicitly | `import std.host (Console)`, optional, since the prelude has it |
| The same helper in two modules | One `pub` declaration in the module it belongs to, imported by the other |
:::

Share as little as the other modules need. Every `pub` declaration is a promise: changing its header changes every module that uses it.

## 11.2.8 Check yourself: names and imports

The app of [A private helper next to a public function](#a-private-helper-next-to-a-public-function) changes one line: `price_tag` now calls `digits` directly, without importing it.

```diff include="steps/07-imports..steps/10-unimported:src/store/app.una" context="0" title="src/store/app.una"
--- a/src/store/app.una
+++ b/src/store/app.una
@@ -15 +15 @@
-  "{product.name}: {format(product.cents)}"
+  "{product.name}: {digits(product.cents)}"
```

Does it check? If not, which code does `una check .` report: U1004, since `digits` is private, or another one?

:::answer Show the answer
It does not check, and the code is U1001, not U1004:

```text include="steps/10-unimported/expected/rendered.txt#L1"
[U1001] Error: cannot find name `digits` in this module, its imports or the prelude
```

The app never imported `digits`, so the name is in none of its three sources: its declarations, its imports and the prelude. U1004 is reported only when an import names a private declaration, as in [Private stays private](#private-stays-private). Either way, the fix is the same: call `format`, which is public and handles every amount.
:::
