typestar

Parametric polymorphism in Odin

One largest() for ints and floats: $T takes the element type at compile time.

package main

import "core:fmt"

// $T takes the element type at compile time -- parametric polymorphism.
largest :: proc(items: []$T) -> T {
    best := items[0]
    for x in items[1:] {
        if x > best do best = x
    }
    return best
}

main :: proc() {
    ints := []int{3, 41, 12, 55}
    floats := []f64{2.5, 8.75, 1.25}
    fmt.println("largest int:", largest(ints))
    fmt.println("largest float:", largest(floats))
}

How it works

  1. items: []$T binds the slice's element type to T per call site.
  2. The body compares with >; each instantiation checks it for its own T.
  3. largest(ints) and largest(floats) compile to two separate procedures.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
391
Tokens
106
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 98 seconds.

Type this snippet

Step 2 of 3 in Types & generics, step 20 of 27 in Language basics.

← Previous Next →