Nyx by Example

Traits

Traits define shared behavior that multiple types can implement. They are Nyx's primary abstraction mechanism — similar to interfaces in Go or type classes in Haskell — but with full method bodies and generic dispatch support.

Code

// Traits: definir Display, implementar para struct, llamar método

trait Display {
    fn to_string(self) -> String
}

struct Point {
    x: int,
    y: int
}

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

struct Color {
    r: int,
    g: int,
    b: int
}

impl Display for Color {
    fn to_string(self) -> String {
        return "rgb(" + int_to_string(self.r) + ", " + int_to_string(self.g) + ", " + int_to_string(self.b) + ")"
    }
}

fn main() -> int {
    let p: Point = Point { x: 3, y: 4 }
    print("Punto: " + p.to_string())

    let c: Color = Color { r: 255, g: 128, b: 0 }
    print("Color: " + c.to_string())

    return 0
}

Output

Punto: (3, 4)
Color: rgb(255, 128, 0)

Explanation

A trait block declares a set of method signatures that any implementing type must provide. Here Display requires a single method to_string that takes the receiver by value and returns a String. The trait itself contains no data — it is purely a behavioral contract.

Each impl Display for T block supplies the concrete body for every method the trait demands. Point formats its fields as a coordinate pair while Color uses CSS rgb() notation. Both structs are otherwise completely independent; the only thing they share is adherence to the Display trait.

Once a struct implements a trait, its methods are called with ordinary dot syntax — p.to_string() dispatches to Point's implementation at compile time (static dispatch). This gives you polymorphism without runtime overhead.

← Previous Next →

Source: examples/by-example/21-traits.nx