Classes

Zen C does not use a class keyword. Instead, it uses struct for data definitions and impl blocks to define methods. The self parameter is implicitly passed by reference, allowing for state mutation without explicit pointer syntax. It also supports a convenient .field shorthand inside methods as an alternative to self.field.

struct Point {
    x: int;
    y: int;
}

impl Point {
    // Constructor convention (static method returning Self)
    fn new(x: int, y: int) -> Self {
        return Point{x: x, y: y};
    }

    // Instance method
    fn print_coords(self) {
        // Using the .field shorthand for self.x and self.y
        println "Point coordinates: ({.x}, {.y})";
    }
    
    // Method that mutates state using 'self' directly
    fn move_by(self, dx: int, dy: int) {
        self.x += dx;
        self.y += dy;
    }
}

fn main() {
    // Instantiate using the constructor
    let p = Point::new(10, 20);
    p.print_coords();
    
    // Mutate state directly
    p.move_by(5, -5);
    
    print "After moving: ";
    p.print_coords();
}

Output:

Point coordinates: (10, 20)
After moving: Point coordinates: (15, 15)

Attribution: This is a community solution for the Rosetta Code task Classes in Zen C.

This article uses material from the Rosetta Code article Classes, which is released under the GNU Free Documentation License 1.3. A list of the original authors can be found in the page history.