---
title: "Generics"
description: "Write one declaration that works over a family of types — parameters, inference, explicit arguments, bounds, and opaque types."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.atoll.workreef.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Generics

A generic declaration is checked once and specialized per use. Type parameters
go in square brackets after the name.

```atoll
fn identity[T](value T) T {
    return value
}

fn main() void {
    n := identity(42)
    s := identity("atoll")
    println("${n} ${s}")
}
```

`identity` is checked as generic source before any call exists. Each call then
gets its own substitution — `identity(42)` does not pin `T` to `int` for
`identity("atoll")`.

## Generic types

Structs, enums, and type aliases take parameters with the same bracket syntax.

```atoll
struct Pair[A, B] {
    first  A
    second B
}

enum Tree[T] {
    Leaf(T)
    Branch([]Tree[T])
}

type Predicate[T] = fn(T) -> bool

fn count_leaves[T](node &Tree[T]) int {
    match node {
        Leaf(_) => 1
        Branch(children) => {
            mut total := 0
            for child in children {
                total = total + count_leaves(child)
            }
            total
        }
    }
}

fn main() void {
    entry: Pair[string, int] = Pair { first: "port", second: 8080 }
    tree := Branch([Leaf(1), Branch([Leaf(2), Leaf(3)])])
    println("${entry.first}=${entry.second} leaves=${count_leaves(tree)}")
}
```

Every use supplies the declared number of arguments, and different arguments
produce unrelated types. `Pair[int, bool]` and `Pair[float, string]` share a
declaration but never a type:

```atoll refused=ATOLL2002
struct Pair[A, B] {
    first  A
    second B
}

fn f() void {
    numeric := Pair { first: 1, second: 2 }
    textual: Pair[string, string] = numeric
}
```

That is rejected with `ATOLL2002: expected Pair[string, string], found
Pair[int, int]`.

## Where a type parameter is in scope

A type parameter is a name for a type in the declaration that writes it, and
nowhere else. Scoping is lexical, as in Rust:

| A parameter of | is in scope in |
| --- | --- |
| a function (`fn f[T]`, a method's `fn m[T]`) | its whole parameter list, every bound in it included, its result, its error type, its `where` clause and its body |
| a struct or an enum | its bounds and `where` clause, its fields or variants, and the methods written inside it, but not a method written outside it (`fn Pair.swap`) or an implementation of it, which declare their own |
| a type alias or an error union | its target, or its members |
| an implementation (`impl[T]`) | its head, its `where` clause, its associated types' bindings, its associated constants and its methods |
| a trait | its bounds, super traits and `where` clause, its associated types' bounds and defaults, its associated constants, and its methods |

An inner parameter hides an outer one of the same name: a method's own `T` is
the method's, not its struct's. A parameter also hides any type of its name,
a struct, an enum, an imported type, a stdlib type or a builtin, wherever it is
in scope:

```atoll
struct Key {
    id int
}

// `Key` here is the parameter, not the struct beside it.
fn pick[Key](a Key, b Key, first bool) Key {
    if first {
        return a
    }
    return b
}

fn main() void {
    k := Key { id: 1 }
    println("${pick(1, 2, true)} ${k.id}")
}
```

Outside its declaration a parameter names nothing, whatever another
declaration of the file binds:

```atoll front-fail=ATOLL1009
enum Slot[Item] {
    Empty
    Full(Item)
}

fn size(x Item) int {
    return 0
}

fn main() int {
    return 0
}
```

`front-fail=ATOLL1009` marks a refusal the new compiler gives. Today's compiler
takes `size`: it drops ATOLL1009 for any name a declaration of the file binds.

## Inference

A call infers its type arguments from the argument types and from the expected
result type at the call site.

```atoll
struct Wrapper[T] { inner T }

fn wrap[T](value T) Wrapper[T] {
    return Wrapper { inner: value }
}

fn main() void {
    // T comes from the argument.
    a := wrap(1)
    // T comes from the annotation on the destination.
    b: Wrapper[string] = wrap("x")
    // An empty literal carries no information, so annotate it directly.
    rows: []int = []
    empty := wrap(rows)
    println("${a.inner} ${b.inner} ${empty.inner.len()}")
}
```

An annotation on a binding or a parameter drives inference when the value
itself carries no information. Note that the annotation applies to the binding
it is written on: `empty: Wrapper[[]int] = Wrapper { inner: [] }` still fails,
because the empty literal inside the struct is checked before the outer
annotation reaches it. Annotate the literal, as above.

## Explicit type arguments

When inference has nothing to work from, or when you want the instantiation
visible in the source, put the arguments in brackets before the call
parentheses.

```atoll
fn width_of[T]() int { return 8 }

fn main() void {
    n := width_of[int]()
    empty := List.new[string]()
    println("${n} ${empty.len()}")
}
```

The brackets bind to a call. Without a following `(...)`, `value[index]` stays
an indexing expression, so the two forms never collide. The `::<T>` and `<T>`
spellings from other languages are not Atoll syntax.

## Bounds

A bare type parameter has no behavior. The body may move values of type `T`
around, but it cannot call methods on them:

```atoll refused=ATOLL2003
trait Summary {
    fn summary(&self) string
}

fn show[T](value T) string {
    return value.summary()
}
```

That is `ATOLL2003: no method summary on type ?1463` — the checker has no
reason to believe every `T` has one. A bound supplies the reason. Write it
inline for a single short requirement:

```atoll
fn largest[T: Comparable[T]](values []T, fallback T) T where T: Clone {
    mut best := fallback
    for value in values {
        if value > best { best = value.clone() }
    }
    return best
}

fn main() void {
    println("${largest([3, 9, 4], 0)}")
}
```

…or in a `where` clause when several parameters or several requirements
interact. `+` combines requirements on one parameter.

```atoll
trait Summary {
    fn summary(&self) string
}

fn render[T, U](left T, right U) string
where T: Summary + Clone, U: Display {
    copy: T = left.clone()
    return "${copy.summary()} / ${right}"
}

struct Note { text string }

impl Summary for Note {
    fn summary(&self) string { return self.text.clone() }
}

impl Clone for Note {
    fn clone(&self) Note { return Note { text: self.text.clone() } }
}

struct Tag { name string }

impl Display for Tag {
    fn write_to(&self, out &mut string) void {
        out.append("#")
        out.append(self.name)
    }
}

fn main() void {
    println(render(Note { text: "hi" }, "queued"))
    println(render(Note { text: "hi" }, Tag { name: "release" }))
}
```

The annotation `copy: T` is required: `Clone::clone` is declared to return
`Self`, and the result of that call does not carry the `Summary` bound on its
own. Annotating the binding puts it back on `T`, where the bound lives.

Bounds are capabilities resolved at check time, not runtime tests. `T: Display`
lets the body call `to_string`; it does not insert a branch asking whether this
particular value implements `Display`.

Which means a bound is only satisfied by an implementation that actually
exists — and when one is missing the report arrives at **instantiation**, as
`ATOLL3100: type ?N does not implement trait Display`, not at the declaration.

```atoll
fn render[U](value U) string
where U: Display {
    return "[${value}]"
}

fn main() void {
    n: int = 42
    println(render(n))
}
```

It compiles: `int` has a `Display` implementation. A bound is checked in
**mono**, when the function is instantiated, so a declaration alone proves
nothing either way.

Bounds also work on the operators those traits back. `Comparable[T]` is what
makes `value > best` legal above, and `Numeric` is what makes `+` legal here:

```atoll
fn total[T](values []T, zero T) T
where T: Numeric, T: Clone {
    mut sum := zero
    for value in values {
        sum = sum + value.clone()
    }
    return sum
}

fn main() void {
    println("${total([1, 2, 3], 0)} ${total([1.5, 2.5], 0.0)}")
}
```

### A bounded call inside a closure

A call inside a closure may rely on the enclosing function's bound. Here
`value.summary()` resolves against `T: Summary`:

```atoll
trait Summary {
    fn summary(&self) string
}

fn labels[T](values []T) []string
where T: Summary {
    return values.map(value => value.summary()).collect()
}
```

That block declares a trait and a generic function and calls neither, so on
its own nothing instantiates `labels`. Instantiated — a `struct` with an
`impl Summary`, and a `main` that calls it — the whole pipeline accepts it.

The same function written as a loop is a perfectly good thing to write too:

```atoll
trait Summary {
    fn summary(&self) string
}

fn labels[T](values []T) []string
where T: Summary {
    mut out: []string = []
    for value in values {
        out.push(value.summary())
    }
    return out
}

struct Note { text string }

impl Summary for Note {
    fn summary(&self) string { return self.text.clone() }
}

fn main() void {
    println("${labels([Note { text: "a" }, Note { text: "b" }]).len()}")
}
```

### `Dup` — a parameter that owes no destructor

One bound is built into the language rather than declared by a `trait`.
`T: Dup` says the parameter is **duplicable**: a second name for a value of
that type is sound, because it is plain data: nothing of that type owes a
destructor or holds a block.

It exists because a generic body cannot otherwise be told. Compare two
bodies that are the same body:

```atoll
fn concrete() int {
    mut xs: []int = List.new[int](4)
    xs.push(1)
    _n := &xs.get(0)
    xs.push(9)
    return 0
}

fn main() void {
    println("${concrete()}")
}
```

That is admitted: `int` owes no destructor, so when `push` reseats the list
onto a bigger block it can carry every element across and nothing runs twice.
The same body over a type parameter is refused, for every `T`:

```atoll refused=ATOLL1070
fn unbounded[T](a T, b T) int {
    mut xs: []T = List.new[T](4)
    xs.push(a)
    _n := &xs.get(0)
    xs.push(b)
    return 0
}

fn main() void {
    println("${unbounded(1, 2)}")
}
```

`unbounded[int]` is refused along with the rest — the instantiation the first
example just showed to be fine — because the signature does not say which kind
of `T` this is. Saying so admits it:

```atoll
fn bounded[T: Dup](a T, b T) int {
    mut xs: []T = List.new[T](4)
    xs.push(a)
    _n := &xs.get(0)
    xs.push(b)
    return 0
}

fn main() void {
    println("${bounded(1, 2)}")
}
```

**The bound admits; it never refuses.** Adding it is how a body asks for more.

The same goes for reading a value twice. A body cannot know what an unbounded
`T` will be, so a value of it has one owner, as a `string` does, and handing it
on twice is refused for every `T`:

```atoll refused=ATOLL3102
fn both[T](x T) []T {
    return [x, x]
}

fn main() void {
    println("${both(1).len()}")
}
```

`T: Dup` says it is plain data, which reads as often as a body likes. `T: Clone`
is the bound for a real second value, and the body says where it pays for one:

```atoll
fn both[T: Clone](x T) []T {
    return [x.clone(), x]
}

fn main() void {
    println("${both("a").len()}")
}
```

A parameter a body only reads is a `&T`, and needs neither.

The promise is checked at the call, not taken on trust. A caller that
instantiates at a type owing a destructor is refused there:

```atoll refused=ATOLL3100
struct Tag { k int }

impl Drop for Tag {
    fn drop(&mut self) void { }
}

fn keep[T: Dup](one T) int {
    return 0
}

fn main() void {
    println("${keep(Tag { k: 1 })}")
}
```

**There is no `impl Dup for` to write**, and that is deliberate. Duplicability
is structural — a type is duplicable when it declares no `Drop` and none of its
parts do — so there is nothing for you to assert about it, and no way to assert
it wrongly. The compiler answers the bound from the type's own shape, using the
same question reference counting asks after specialization.

A struct's type parameter carries it the same way:

```atoll
struct Holder[T: Dup] {
    one T
}

fn main() void {
    h := Holder[int] { one: 7 }
    println("${h.one}")
}
```

## Generic implementations

An `impl` block can carry its own parameters. Declare them after `impl` and use
them in the target type.

```atoll
struct Box[T] { value T }

impl[T] Box[T] {
    fn get(&self) &T => self.value

    fn replace(&self, next T) Box[T] => Box { value: next }
}

fn main() void {
    b := Box { value: 3 }
    println("${b.replace(9).get()}")
}
```

A trait implementation can be *conditional*: it applies only when its bounds
hold for the arguments.

```atoll
struct Box[T] { value T }

impl[T] Equatable for Box[T]
where T: Equatable {
    fn equals(&self, other Box[T]) bool {
        return self.value == other.value
    }
}

fn main() void {
    println("${Box { value: 3 } == Box { value: 3 }}")
}
```

`Box[Token]` satisfies `Equatable` only when `Token` does. A *blanket*
implementation goes further and targets a type variable directly:

```atoll
trait Printable: Display + Debug {}

impl[T] Printable for T
where T: Display + Debug {}

struct Tag { name string }

impl Display for Tag {
    fn write_to(&self, out &mut string) void { out.append(self.name) }
}

impl Debug for Tag {
    fn write_debug_to(&self, out &mut string) void {
        out.append("Tag(")
        out.append(self.name)
        out.append(")")
    }
}

fn emit[T](value T) string
where T: Printable {
    return value.to_string()
}

fn main() void {
    println(emit(Tag { name: "release" }))
}
```

Blanket implementations are project-wide policy — see
[Implementations](https://docs.atoll.workreef.dev/language/types/implementations/) for the coherence rules
that keep two of them from overlapping.

## Self

Inside a trait, `Self` names the implementing type, which lets a requirement
relate its inputs and outputs without a second type parameter.

```atoll
trait Merge {
    fn merge(&self, other &Self) Self
}

struct Bag { count int }

impl Merge for Bag {
    fn merge(&self, other Bag) Bag {
        return Bag { count: self.count + other.count }
    }
}

fn fold_all[T](values []T, seed T) T
where T: Merge {
    mut acc := seed
    for value in values {
        acc = acc.merge(value)
    }
    return acc
}

fn main() void {
    total := fold_all([Bag { count: 1 }, Bag { count: 2 }], Bag { count: 0 })
    println("${total.count}")
}
```

In the implementation, `Self` written as a type is the owner, `Bag`, as in any
method. Today's compiler does not read it so and refuses it, so the example
writes `Bag`.

## Opaque types

`impl Trait` names "some type satisfying this contract" without naming which.

```atoll
trait Shape {
    fn area(&self) float
}

struct Square { side float }
struct Circle { radius float }

impl Shape for Square {
    fn area(&self) float { return self.side * self.side }
}

impl Shape for Circle {
    fn area(&self) float { return 3.14159 * self.radius * self.radius }
}

fn describe(shape impl Shape) string {
    return "area ${shape.area()}"
}

fn main() void {
    println(describe(Square { side: 2.0 }))
    println(describe(Circle { radius: 1.0 }))
}
```

In parameter position, each call supplies one concrete argument satisfying the
trait, and the body is specialized per argument type — `impl Shape` there is
shorthand for an anonymous type parameter bounded by `Shape`.

In return position, the declaring function owns one hidden concrete type:
callers may use the promised behavior but cannot name the representation, and
two functions returning `impl Shape` do not share an opaque type even when
their bodies currently return the same struct.

Return-position `impl Trait` type-checks today, but the opaque result does not
survive lowering: calling a trait method on it, or passing it where the bound
must be re-proved, fails at build time.

```atoll fail
trait Shape {
    fn area(&self) float
}

struct Square { side float }

impl Shape for Square {
    fn area(&self) float { return self.side * self.side }
}

fn unit_square() impl Shape {
    return Square { side: 1.0 }
}

fn main() void {
    shape := unit_square()
    println("${shape.area()}")
}
```

Until that is finished, return the concrete type — `fn unit_square(): Square` —
and keep `impl Trait` for parameters.

Atoll uses static dispatch throughout. There is no `dyn Trait`, no vtable, and
no downcast. When alternatives must stay open at runtime, use an enum or an
[anonymous union](https://docs.atoll.workreef.dev/language/types/unions/).

## Compile-time type matching

`match T` selects on a type parameter at specialization time.

```atoll
fn width_code[T]() int {
    return match T {
        u8 => 1
        u16 => 2
        u32 => 4
        else => 0
    }
}

fn main() void {
    println("${width_code[u8]()} ${width_code[u32]()} ${width_code[int]()}")
}
```

Each arm is resolved once per instantiation, so the specialized body contains
only the selected branch. This is not a runtime `value is Type` test — there is
no value involved.

## Errors and effects

A generic callable can carry fallibility through a function parameter. `E` is
an ordinary type parameter that happens to sit on the error channel.

```atoll
error CheckError { Rejected }

fn keep_all[T, E](values []T, check fn(T) -> Result[T, E]) []T ! E {
    mut out: []T = []
    for value in values {
        out.push(check(value)?)
    }
    return out
}

fn require_positive(n int) int ! CheckError {
    if n <= 0 { error Rejected }
    return n
}

fn run() []int ! CheckError {
    return keep_all([1, 2, 3], require_positive)?
}

fn main() void {
    empty: []int = []
    println("${run().unwrap_or(empty).len()}")
}
```

A closure works in the same position: `keep_all([1, 2, 3], n => require_positive(n))`
infers `T = int` and `E = CheckError` identically.

Note the spelling of the parameter type. `T ! E` is sugar available on a
*declaration's* return type; inside a function **type** the fallible result must
be written out as `Result[T, E]`. The sugared form does not unify with the
function it is meant to accept:

```atoll refused=ATOLL2002
error CheckError { Rejected }

fn keep_all[T, E](values []T, check fn(T) -> T ! E) []T ! E {
    mut out: []T = []
    for value in values {
        out.push(check(value)?)
    }
    return out
}

fn require_positive(n int) int ! CheckError {
    if n <= 0 { error Rejected }
    return n
}

fn run() []int ! CheckError {
    return keep_all([1, 2, 3], require_positive)?
}
```

That reports `ATOLL2002: expected fn(int) -> int ! ?1470, found
fn(int) -> Result[int, CheckError]`.

The error type stays concrete at each use, so `keep_all` does not erase which
failures a caller must handle. The same holds for effects: passing a suspending
closure keeps `Suspend` on the row. Genericity never makes a host operation
pure — see [Effects](https://docs.atoll.workreef.dev/language/concurrency/effects/).

## Recursive generics

A recursive generic type needs a representational break, exactly as a
non-generic one does. A managed container supplies it.

```atoll
enum Node[T] {
    Empty
    Children([]Node[T])
}

fn depth[T](node &Node[T]) int {
    match node {
        Empty => 0
        Children(kids) => {
            mut best := 0
            for kid in kids {
                d := depth(kid)
                if d > best { best = d }
            }
            best + 1
        }
    }
}

fn main() void {
    tree: Node[int] = Children([Empty, Children([Empty])])
    println("${depth(tree)}")
}
```

A payload holding `Node[T]` inline with no indirection has no finite size and
is rejected.

## Monomorphization

The compiler specializes each reachable combination of type arguments: generic
functions, methods, closures, and layouts all become concrete before codegen.
That is what makes direct calls and flat field layouts possible.

Specialization is an implementation strategy, not permission to inspect a type
parameter without a bound. The order is:

1. check the generic body against its declared bounds only;
2. infer or read concrete arguments at each reachable use;
3. substitute types, associated types, methods, errors, and effects;
4. reuse an existing specialization with the same canonical arguments, or make
   one;
5. lower and validate the concrete body.

A failure at step 1 belongs at the declaration; a failure caused by a
particular substitution should name both the declaration and the instantiating
call. Many distinct instantiations cost code size, so prefer one generic
algorithm over hand-written copies — but do not invent wrapper types just to
force extra specializations.

## A composed example

A paginated result type: one generic struct, an inherent generic `impl`, a
static constructor, and a generic function over it.

```atoll
struct Page[T] {
    items       []T
    next_cursor string?
}

impl[T] Page[T] {
    fn empty() Page[T] => Page { items: [], next_cursor: None }

    fn len(&self) int => self.items.len()

    fn is_last(&self) bool => self.next_cursor.is_none()
}

fn paginate[T: Clone](all []T, size int) Page[T] {
    if all.len() <= size {
        return Page { items: all, next_cursor: None }
    }
    return Page {
        items: all.take(size).map(x => x.clone()).collect(),
        next_cursor: Some("${size}")
    }
}

fn describe[T](page Page[T]) string
where T: Display {
    mut joined := ""
    for item in page.items {
        if joined.len() > 0 { joined += ", " }
        joined += "${item}"
    }
    suffix := if page.is_last() { "end" } else { "more" }
    return "${joined} (${suffix})"
}

fn main() void {
    names := paginate(["ada", "bob", "cy", "dee"], 2)
    numbers := paginate([1, 2, 3, 4, 5], 2)
    blank: Page[string] = Page.empty()
    println(describe(names))
    println("${numbers.len()} ${numbers.is_last()}")
    println("${blank.len()} ${blank.is_last()}")
}
```

`Page` is declared once; `Page[int]` and `Page[string]` are two independent
static instantiations of that source. `paginate` is specialized for both;
`describe` only for `Page[string]`, because that is the one whose element type
satisfies its `Display` bound.

Source: https://docs.atoll.workreef.dev/language/types/generics/index.mdx
