Traits — Mapanare

Generic abstractions over types — define shared behavior without inheritance.

Overview

Traits define shared behavior that types can implement. They are Mapanare's answer to interfaces — without classes, inheritance, or virtual dispatch. Traits enable bounded generics.

Defining a Trait

trait Display { fn to_string(self) -> String }
trait Ord { fn cmp(self, other: Self) -> Int }
trait Eq { fn eq(self, other: Self) -> Bool }
trait Hash { fn hash(self) -> Int }

Implementing a Trait

impl Display for Point {
    fn to_string(self) -> String {
        return str(self.x) + ", " + str(self.y)
    }
}

Trait Bounds on Generics

fn max<T: Ord>(a: T, b: T) -> T {
    if a.cmp(b) > 0 { return a }
    return b
}

Builtin Traits

Display (to_string), Eq (equality), Ord (ordering comparison), Hash (hash value for maps/sets).

Code Generation

Python backend: Traits emit as typing.Protocol classes. LLVM backend: Monomorphization — generic functions are specialized per concrete type at call sites.