Nyx by Example

Structs

Structs let you group related data under a named type. You attach behavior to a struct with an impl block, giving it methods that operate on its fields through a self parameter.

Code

// Structs: definición, campos, impl con métodos, instanciación

struct Point {
    x: int,
    y: int
}

impl Point {
    fn distance_from_origin(self) -> int {
        // distancia Manhattan: |x| + |y|
        var ax: int = self.x
        if ax < 0 {
            ax = ax * -1
        }
        var ay: int = self.y
        if ay < 0 {
            ay = ay * -1
        }
        return ax + ay
    }

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

struct Rectangle {
    width: int,
    height: int
}

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

fn main() -> int {
    let p1: Point = Point { x: 3, y: 4 }
    print("Punto: " + p1.to_string())
    print("Distancia al origen: " + int_to_string(p1.distance_from_origin()))

    let p2: Point = Point { x: -2, y: 5 }
    print("Punto: " + p2.to_string())
    print("Distancia al origen: " + int_to_string(p2.distance_from_origin()))

    let rect: Rectangle = Rectangle { width: 6, height: 7 }
    print("Area del rectangulo: " + int_to_string(rect.area()))

    return 0
}

Output

Punto: (3, 4)
Distancia al origen: 7
Punto: (-2, 5)
Distancia al origen: 7
Area del rectangulo: 42

Explanation

A struct is defined with the struct keyword, a name, and a comma-separated list of typed fields inside curly braces. Struct names follow PascalCase by convention. Fields are accessed with dot notation: instance.field.

Methods are defined in an impl block for the struct. The first parameter self refers to the instance the method is called on — it is similar to this in other languages. Methods can access any field of the struct through self.field_name.

Struct instantiation uses the field-initialization syntax: TypeName { field: value, ... }. Every field must be provided; there are no default values unless you write a constructor method explicitly.

The Manhattan distance example shows how methods can contain arbitrary logic, local variables, and control flow — they are just functions scoped to a type. Multiple impl blocks can exist for the same struct, and each struct can have its own independent impl.

← Previous Next →

Source: examples/by-example/08-structs.nx