Oxeon / Examples / Traits and generics

Traits and generics

Traits, default methods, associated types, trait bounds, impl Trait and dyn Trait in Oxeon.

Partly works today

Traits with default methods, generic functions with trait bounds (monomorphized for each set of type arguments), &dyn Trait and Box<dyn Trait> compile today. Not yet: associated types (Container), slices (largest, hit_all), impl Trait (evens), supertraits and blanket impls (Greeter), and String.

A trait declares methods that types implement, and a method can have a default body (is_dead). Container has an associated type, Item, which each implementation chooses.

Bounds restrict generic parameters, either inline (T: PartialOrd + Copy) or in a where clause. Generics are monomorphized: each set of type arguments gets its own compiled copy, so there’s no runtime cost.

impl Trait in return position hides the concrete type. dyn Trait gives shared code over values of different types: a &dyn Trait is a pointer plus the type’s method table, and calls go through that table.

impl<T: Named> Greeter for T {} is a blanket implementation: every type that implements Named also gets Greeter.

04_traits_generics.ox

examples/syntax/04_traits_generics.ox
// Traits, generics, associated types and trait objects.

pub trait Damageable {
    fn health(&self) -> f32;
    fn apply_damage(&mut self, amount: f32);

    // Default method.
    fn is_dead(&self) -> bool {
        self.health() <= 0.0
    }
}

pub trait Container {
    type Item;
    fn get(&self, index: usize) -> Option<&Self::Item>;
}

struct Stack<T> {
    items: Vec<T>,
}

impl<T> Container for Stack<T> {
    type Item = T;

    fn get(&self, index: usize) -> Option<&T> {
        self.items.get(index)
    }
}

// Bounds inline and in `where` clauses. Generics are monomorphized.
fn largest<T: PartialOrd + Copy>(values: &[T]) -> T {
    let mut best = values[0];
    for &v in values {
        if v > best {
            best = v;
        }
    }
    best
}

fn print_all<C>(container: &C, len: usize)
where
    C: Container,
    C::Item: core::fmt::Debug,
{
    for i in 0..len {
        if let Some(item) = container.get(i) {}
    }
}

// `impl Trait` in argument and return position.
fn evens(limit: u32) -> impl Iterator<Item = u32> {
    (0..limit).filter(|n| n % 2 == 0)
}

// `dyn Trait`: shared code through a vtable.
fn hit_all(targets: &mut [Box<dyn Damageable>], amount: f32) {
    for target in targets.iter_mut() {
        target.apply_damage(amount);
    }
}

// Generic impls and trait inheritance.
pub trait Named {
    fn name(&self) -> String;
}

pub trait Greeter: Named {
    fn greet(&self) -> String {
        format!("hello, {}", self.name())
    }
}

impl<T: Named> Greeter for T {}