# Generics

Generics let one function, struct, or contract work across many concrete types. In Vex, generic code is monomorphized, so the generated code is specialized per concrete use.

## Generic functions

The most common pattern is a reusable function with one or more type parameters:

```vex
fn identity<T>(x: T): T {
    return x;
}

fn pair_first<A, B>(a: A, b: B): A {
    return a;
}
```

You can call generic functions with inference:

```vex
let a = identity(42);
let b = identity("hello");
```

Or with explicit type arguments when clarity matters:

```vex
let first = pair_first<i32, i64>(10, 20);
```

## Generic structs

```vex
struct Container<T> {
    public:
    value: T,
}

struct Pair<T, U> {
    public:
    left: T,
    right: U,
}
```

This is the standard way to build reusable collections, wrappers, and data-model helpers.

### Struct literal inference

A literal can infer its owner arguments through a field's structure, not only
when the field is directly `T`. References, typed pointers, tuples, arrays,
function signatures and nested nominal generic types contribute constraints.

```vex
struct Record { public: value: i32 }
struct Slot<T> { public: source: &T }

let record = Record { value: 997 };
let slot = Slot { source: &record }; // Slot<Record>
```

All occurrences of one parameter must agree, or admit the ordinary value
coercions required by the selected field type. Numeric widening does not permit
reinterpreting reference pointees or incompatible function-pointer signatures.
A missing constraint requires an explicit type/context or a declared default;
contradictory constraints are an error, not a reason to use a default.

Fixed array extents can also infer a const parameter. Mixed type/const arguments
retain declaration order, including inside a nested generic owner:

```vex
struct Samples<T, const N: usize, U> {
    public:
    values: [T; N],
    extra: &U,
}

let samples = Samples { values: [10, 11, 12], extra: &record };
// Samples<i32, 3, Record>
```

Two fields constraining the same `N` to different lengths are rejected. This
does not introduce general symbolic equation solving for const expressions.
Nested types and contract bounds belong to the selected declaration's module;
an import alias or a same-spelled local type does not replace that identity.

## Generic methods

Generic types use normal receiver syntax for methods:

```vex
struct Wrapper<T> {
    public:
    value: T,
}

fn (self: &Wrapper<T>) get(): &T {
    return &self.value;
}

fn (self: &Wrapper<T>!) set(new_value: T) {
    self.value = new_value;
}
```

## Contract bounds

Bounds let you say what operations a type parameter must support.

```vex
contract Stringify {
    toString(): string;
}

fn print_item<T: Stringify>(item: T) {
    let s = item.toString();
    $println(s);
}
```

Use bounds when a function depends on behavior, not on one exact type.

## Default type parameters

Struct parameters can have defaults, including a preceding type parameter:

```vex
struct Defaulted<T = i64> { public: value: T }
struct Tagged<T, Tag = T> { public: value: T }

let inferred = Defaulted { value: 42 as i32 }; // Defaulted<i32>
let explicit: Defaulted<i64> = Defaulted { value: 42 as i32 };
let tagged = Tagged { value: 42 as i32 }; // Tagged<i32, i32>
```

An explicit owner or matching expected owner supplies the field context.
Otherwise, field inference runs first and defaults fill only unconstrained
slots. A default never masks conflicting field types.

Contracts can provide defaults for type parameters. A common pattern is `Self`:

```vex
contract Combine<Rhs = Self> {
    combine(other: Rhs): Self;
}
```

That lets a custom contract accept either its own type or a specified input
type. It does not redefine the prelude `Add` contract.

## Associated types

An associated type names an output selected by an implementation of a contract. The [complete `NextInt` example](contracts.md#associated-types) declares `type Item`, implements the mutable `next()!` requirement for `Counter`, and calls it through a generic contract bound.

## Const generics

Use const generics when part of the type is a compile-time value:

```vex
struct Matrix<T, const N: usize, const M: usize> {
    public:
    rows: [[T; M]; N],
}

fn elementCount<const N: usize, const M: usize>(): usize {
    return N * M;
}
```

This is useful for fixed-size math structures, static buffers, and shape-encoded APIs.

## Practical guidance

- Keep type parameter lists short and purposeful.
- Add bounds only where operations actually require them.
- Prefer inference for callers, explicit type arguments for docs and tricky code.
- Use const generics when the size or shape is part of correctness.

## See also

- [Contracts](contracts.md)
- [Structs](structs.md)
- [Enums](enums.md)
