docs

#Generics

On this page

Use generics when you want the same logic to work for many types. Nabi generics are compiled separately for each concrete type they're called with (monomorphization), so they run as fast as hand-written per-type functions.

#Generic functions

Declare type parameters in <T> after the function name and use them in the parameter and return types. At the call site you usually don't write the type; the compiler infers it from the arguments.

nabi
fn first_or<T>(xs: List<T>, fallback: T) -> T {
    xs.first() ?? fallback
}

println(f"{first_or([10, 20], 0)}");
println(first_or(["a", "b"], "-"));
let empty: List<f64> = [];
println(f"{first_or(empty, 1.5)}");
10
a
1.5

Within one call, T is a single type. Passing different types, as in first_or([1, 2], "x"), is a compile error.

#Trait bounds

With an unbounded T, all you can do is move values around. To compare or add them, require the needed traits with a bound such as T: Ord. Join multiple bounds with +. The compiler checks a generic body against its bounds alone, so the body cannot break no matter which type it's called with.

nabi
fn largest<T: Ord>(xs: List<T>) -> T? {
    let best = xs.first()?;
    for x in xs {
        if x > best { best = x; }
    }
    best
}

println(f"{largest([3, 9, 2]):?}");
println(f"{largest(["pear", "apple"]):?}");
let none_here: List<i32> = [];
println(f"{largest(none_here):?}");
9
"pear"
none

With T: num::Zero, you can also call static methods on the type parameter, such as T::zero().

nabi
fn sum<T: num::Zero + ops::Add<Output = T>>(xs: List<T>) -> T {
    let acc = T::zero();
    for x in xs { acc = acc + x; }
    acc
}

println(f"{sum([1, 2, 3])} {sum([0.5, 0.25])}");
6 0.75

#The body is checked against its bounds

A generic body is type-checked once, on its own, before any call is looked at. Inside it, T supports only what its bounds promise, plus what every type supports: moving, storing into any, forming T | none, and is. Forgetting a bound is an error in the body, even if every call passes a type that would work.

nabi
fn double<T>(x: T) -> T { x + x }
error[E0054]: operator `+` on `T` needs the bound `T: Add`
  --> main.nabi:1:27
   |
 1 | fn double<T>(x: T) -> T { x + x }
   |                           ^^^^^

With the bound added, the same body compiles for every type that has Add. The operations that need no bound work without one.

nabi
fn double<T: ops::Add<T, Output = T>>(x: T) -> T { x + x }
fn keep<T>(x: T, yes: bool) -> T | none { if yes { x } else { none } }
fn boxed<T>(x: T) -> any { x }

println(f"{double(21)} {double(1.5)}");
println(f"{keep("a", true):?} {keep(1, false):?}");
println(f"{boxed(3) is i64}");
42 3
"a" none
true

Because of this rule, a library's generic function that compiles for you compiles for everyone who calls it; an error never surfaces at a distant call site. Trait default methods are checked the same way, with Self known only through the trait. A function with untyped parameters (an implicit generic, below) is the exception.

A bound can name the same trait twice with different parameters. Each use in the body picks the bound whose parameter matches the argument's type, just as an operator picks among a type's impls.

nabi
struct Meters { v: f64; }
impl ops::Add<i32> for Meters { type Output = Meters; fn add(self, rhs: i32) -> Meters { Meters { v: self.v + rhs as f64 } } }
impl ops::Add<f64> for Meters { type Output = Meters; fn add(self, rhs: f64) -> Meters { Meters { v: self.v + rhs } } }

fn nudge<T: ops::Add<i32, Output = T> + ops::Add<f64, Output = T>>(x: T) -> T {
    (x + 1) + 0.5          // Add<i32>, then Add<f64>
}

println(f"{nudge(Meters { v: 2.0 }).v}");
3.5

#where clauses

When bounds get long, moving them to a where clause at the end of the signature makes it easier to read. The meaning is the same.

nabi
fn join_all<T>(xs: List<T>, sep: str) -> str
where
    T: Display,
{
    let out = StrBuf::new();
    for i in 0..xs.len() {
        if i > 0 { out.push_str(sep); }
        out.push_str(f"{xs[i]}");
    }
    out.to_str()
}

println(join_all([1, 2, 3], ", "));
println(join_all([true, false], " / "));
1, 2, 3
true / false

#Generic structs and impl

Structs and enums can take type parameters too. When adding methods, declare the parameters on the impl as well, as in impl<A, B> Pair<A, B>.

nabi
struct Pair<A, B> { first: A; second: B; }

impl<A, B> Pair<A, B> {
    fn swap(self) -> Pair<B, A> {
        Pair { first: self.second, second: self.first }
    }
}

let p = Pair { first: 1, second: "one" };
let q = p.swap();
println(f"{q.first} {q.second}");
one 1

#Defaults

A type parameter can declare a default: struct Vec3<T = f32>. Written as a type, Vec3 is Vec3<f32>. In an expression the parameter is inferred like any other, in this order: a written argument (Vec3::<f64>::new), then the expected type and later uses, then the parameter's default, and last the literal defaults i64 / f64. So unsuffixed literals that fill T are f32 unless something says otherwise. Nothing is converted: a typed argument fixes T itself.

nabi
struct Vec3<T = f32> { x: T; y: T; z: T; }

impl<T> Vec3<T> {
    fn new(x: T, y: T, z: T) -> Vec3<T> { Vec3 { x: x, y: y, z: z } }
}

impl Vec3<f32> { const X: Vec3<f32> = Vec3 { x: 1.0, y: 0.0, z: 0.0 }; }
impl Vec3<f64> { const X: Vec3<f64> = Vec3 { x: 1.0, y: 0.0, z: 0.0 }; }

let a = Vec3::new(1.0, 2.0, 3.0);           // the default: Vec3<f32>
let b: Vec3<f64> = Vec3::new(1.0, 2.0, 3.0); // the expected type first
let x: f64 = 0.5;
let c = Vec3::new(x, 0.0, 0.0);             // x fixes T: Vec3<f64>
let d: Vec3<f64> = Vec3::X;                 // Vec3<f64>'s X
println(f"{a.type_name_of_val()} {b.type_name_of_val()} {c.type_name_of_val()} {d.x}");
Vec3 Vec3<f64> Vec3<f64> 1

Vec3::X takes its instance the same way: from the expected type, else from the one impl that defines X, else the default. A function's default (fn zero<T: Num = f32>() -> T) is a fallback too: let r = zero(); is an f32 unless a later use of r wants another type.

#Associated types

To let each implementation of a trait pick one type, declare an associated type type Item;. Inside the trait, refer to it as plain Item; in generic code outside, as C::Item. The standard Iterator works this way (next chapter).

nabi
trait Container {
    type Item;
    fn get(self, i: usize) -> Item | none;
    fn first(self) -> Item | none { self.get(0) }
}

struct Shelf { books: List<str>; }

impl Container for Shelf {
    type Item = str;
    fn get(self, i: usize) -> str? { self.books.get(i) }
}

fn first_of<C: Container>(c: C) -> C::Item | none { c.first() }

let s = Shelf { books: ["Dune", "Emma"] };
println(f"{first_of(s):?} {s.get(5):?}");
"Dune" none

It is an associated type rather than a type parameter because Item is fixed to exactly one type for a given implementor. Users don't need to spell out Shelf's element type. Every impl gives each associated type the trait declares without a default: leaving type Item = ..; out is an error (E0072) whose help writes the line, taking the type from the impl's methods when they name it.

#Advanced: const generics

You can skip this section on a first read. A parameter can also be a compile-time value instead of a type. Use this when a value is part of a type, like the length of a fixed-size array [T; N].

nabi
fn total<const N: usize>(a: [i32; N]) -> i32 {
    let s = 0;
    for i in 0..N { s += a[i]; }
    s
}

let a: [i32; 4] = [1, 2, 3, 4];
let z: [f64; 3] = [0.5; 3];
println(f"{total(a)} {a.len()} {z:?}");
10 4 [0.5, 0.5, 0.5]

const parameters can only be integers, bool, or char.

A check on a const parameter goes in a const { .. } block. It runs at compile time, once for each length the function is called with, so halves([1, 2, 3]) is a compile error at that call, not a panic when it runs. A const inside the function may read N too, and has a value for each length:

nabi
fn halves<const N: usize>(a: [i32; N]) -> ([i32; N / 2], [i32; N / 2]) {
    const { assert(N % 2 == 0, "halves needs an even length") };
    const HALF: usize = N / 2;
    let l: [i32; N / 2] = [0; N / 2];
    let r: [i32; N / 2] = [0; N / 2];
    for i in 0..HALF {
        l[i] = a[i];
        r[i] = a[HALF + i];
    }
    (l, r)
}

let (l, r) = halves([1, 2, 3, 4]);
println(f"{l:?} {r:?}");
[1, 2] [3, 4]

#Hiding a return type: some

Iterator adapters and closures have long types you don't want in a signature. -> some Trait returns one concrete type that callers see only as Trait: the body picks it, calls stay static, and you can change the body without changing the signature. It works on pub functions too.

nabi
pub fn evens(n: i32) -> some Iterator<Item = i32> {
    (0..n).filter(|x| x % 2 == 0)
}

fn adder(k: i32) -> some fn(i32) -> i32 {
    |x| x + k
}

println(evens(10).map(|x| x * x).sum());
println(adder(3)(4));
120
7

A caller may use only what the bound gives: evens(10).contains(4) is an error, since Iterator has no contains. The body returns one type; to return different types from different paths, write -> any Trait.

#Taking any type with a trait: some parameters

A parameter written x: some Trait takes any type with Trait, without naming a type parameter: fn show(x: some Display) is fn show<T: Display>(x: T). Each call has one static type, the argument's, and each some parameter is its own type.

nabi
fn show(x: some Display) -> str { f"<{x}>" }
fn both(a: some Display, b: some Display) -> str { f"{a} {b}" }
fn twice(f: some fn(i32) -> i32, x: i32) -> i32 { f(f(x)) }

println(show(5));
println(both("hi", 2.5));
println(twice(|x| x * 3, 2));
<5>
hi 2.5
18

The type has no name, so a call can't choose it with ::<..>; declare <T: Trait> when it should. some is the static counterpart of any Trait: some is one type, fixed at each call or by the body, while any holds a value of any such type and dispatches at run time.

#Naming a hidden type: type X = some Trait

A -> some Trait type has no name, so you can't keep it in a struct field or write it in another signature. type X = some Trait; gives it one. The functions of X's module that return X define it: their bodies pick the one concrete type, as with -> some. Every other module can store X in fields, let x: X and List<X>, pass it and return it, and sees only the bound.

Inside nums, Evens is the concrete filter type, so its functions can use all of it. Outside, only Iterator is there: b.items.len() is an error, and so is let n: i64 = .. for a some Display type (E0146). The module needs at least one function that returns Evens, and all of them must give the same type (E0145). Calls and fields stay static: a Batch holds the filter itself, with no box. type X = any Trait is something else, a plain alias of a dynamic slot whose values may each have a different type.

some goes in those three places only. A field or a type argument written some Trait is an error; name the type with type, as Evens does, or declare <T: Trait>:

nabi
struct Label {
    text: some Display;
}
error[E0010]: `some Trait` is only a function's parameter or return type, or the whole right side of a `type` alias
  --> main.nabi:2:11
   |
 2 |     text: some Display;
   |           ^^^^
   |
   = help: for a variable, leave the type out (`let x = ..`); for a field or a type argument, declare `<T: Trait>` and write `T`, or name the type with `type Name = some Trait;`; for a value of several types, write `any Trait`

#A fast path for one type

Sometimes one element type deserves its own code, say an f32 kernel, while every other type keeps the generic one. Test the type parameter itself with if T is f32. Inside the branch T is f32: xs is a List<f32>, and an f32 result is a T. Each instance keeps only the branch its type takes, so the test costs nothing at run time.

nabi
fn sum_f32(xs: List<f32>) -> f32 { xs.sum() }

fn total<T: num::Num + Clone>(xs: List<T>) -> T {
    if T is f32 {
        return sum_f32(xs);      // here xs is a List<f32>, and an f32 is a T
    }
    let acc = T::zero();         // every other type: the generic path
    for x in xs { acc = acc + x; }
    acc
}

let a: List<f32> = [1.5, 2.5];
let b: List<i64> = [1, 2, 3];
println(f"{total(a)} {total(b)}");
4 6

The branch is still checked once, at the definition, and only it knows T: the else branch and the code after the if are ordinary generic code. Types are compared with is, not ==.

Pick between this and a trait by whether the set of types is open:

  • Use a trait when each type needs its own behaviour and new types should join later. An impl per type says exactly that, and a type with no impl is a compile error.
  • Use if T is for a fast path that keeps a generic fallback. A chain like if T is f32 { .. } else if T is f64 { .. } else { panic(..) } is a closed set of types in disguise; nabi lint flags it (closed_type_switch) and suggests the trait.

#Generics and any

Generics are static. When you instead need a slot whose value's type may change at runtime, write any explicitly. Narrow any values with is before use. Dynamic dispatch costs appear only where you wrote any.

nabi
let v: any = 1;
println(f"{v is i64}");
v = "text";
if v is str {
    println(f"now a string, length {v.len()}");
}
true
now a string, length 4

The spec defines a function with omitted parameter types, fn show_sum(x, y), as an implicit generic, not as any. Only a function that is not pub or pub(pkg) may omit them; a pub one writes every parameter type (E0138). No bounds are inferred: the function is monomorphized at each call site, and each copy of the body is checked with that call's argument types, so an error points into the body and at the call that caused it.

nabi
fn show_sum(x, y) { println(f"{x + y}"); }   // implicit generic: fn show_sum<T, U>(x: T, y: U)

show_sum(1, 2);       // 3
show_sum(1.5, 2.0);   // 3.5
3
3.5

#Summary

  • Declare generics with fn f<T>(..), struct S<A, B>, and impl<A, B> S<A, B>. Type arguments are usually inferred.
  • Bounds like T: Ord + Clone determine which operations the body may use. Move long ones to a where clause.
  • A type parameter's default (struct Vec3<T = f32>) applies where nothing else fixes the parameter; unsuffixed literals filling it take it.
  • An associated type type Item; is fixed to one type per implementation, which every impl must give unless the trait has a default, and is written C::Item from outside.
  • const N: usize takes a value as a type parameter.
  • -> some Trait returns one hidden concrete type that callers use only through Trait; x: some Trait takes any type with Trait, one per call; type X = some Trait; names a hidden type, fixed by its module's functions, for fields and signatures.
  • if T is f32 { .. } gives one type a fast path inside a generic body; a trait is for an open set of types.
  • Generics are static (monomorphized); any is a dynamic slot that exists only where you write it.

#Further reading

Found a mistake? Edit this page on GitHub. Last updated