BRAIDGROUP
RESEARCH & DEV
13. Documentation

Traits and Interfaces

Current Status

Braid v1 does not have explicit traits or interfaces as a language feature. The parser does not include a trait or interface keyword. Code organization and polymorphism are achieved through impl blocks and struct composition patterns. Full trait support is planned for a future version.

The impl Pattern

The impl block serves as the primary mechanism for grouping behavior associated with a type. This provides a form of ad-hoc polymorphism: any struct can have methods that define its behavior.

struct Vector2 {
    x: float;
    y: float;
}

impl Vector2 {
    fn magnitude(self) -> float {
        return sqrt(self.x * self.x + self.y * self.y);
    }

    fn normalize(self) -> Vector2 {
        let mag = self.magnitude();
        return Vector2 { x: self.x / mag, y: self.y / mag };
    }
}

struct Vector3 {
    x: float;
    y: float;
    z: float;
}

impl Vector3 {
    fn magnitude(self) -> float {
        return sqrt(self.x * self.x + self.y * self.y + self.z * self.z);
    }
}

Struct Composition

Instead of trait inheritance, Braid encourages struct composition. Embed one struct inside another to reuse behavior. This is explicit and straightforward.

struct Named {
    name: string;
}

impl Named {
    fn get_name(self) -> string {
        return self.name;
    }

    fn set_name(self, new_name: string) {
        self.name = new_name;
    }
}

struct User {
    named: Named;
    email: string;
    age: int;
}

fn main() {
    let user = User {
        named: Named { name: "Alice" },
        email: "alice@example.com",
        age: 30,
    };
    print(user.named.get_name());
}

Shared Behavior via Helper Functions

When multiple structs need the same behavior, write standalone functions that operate on compatible struct fields. This avoids the need for trait dispatch.

fn print_area(shape: Shape) {
    let a = shape.area();
    print("area: " + a);
}

struct Rectangle {
    width: float;
    height: float;
}

impl Rectangle {
    fn area(self) -> float {
        return self.width * self.height;
    }
}

struct Triangle {
    base: float;
    height: float;
}

impl Triangle {
    fn area(self) -> float {
        return 0.5 * self.base * self.height;
    }
}

Future Plans

Full trait support is planned for a future version of Braid. The design will include:

  • trait keyword for defining shared interfaces
  • impl Trait for Type syntax for implementing traits
  • Trait bounds on generic parameters
  • Default method implementations
  • Trait objects for dynamic dispatch

Until then, struct composition and the impl pattern cover most use cases while keeping the language simple and the compiler pipeline lean.