Oxeon / Examples / Structs and enums

Structs and enums

Structs, tuple and unit structs, enums whose variants carry data, impl blocks, methods and associated constants in Oxeon.

Partly works today

Structs, enums, impl blocks, methods and match on enums compile today. Vec and float methods such as sqrt work too. Not yet: struct update syntax (..a).

Structs come in three forms: with named fields (Vec2), tuple structs (Meters(pub f32)) and unit structs (Marker). pub controls visibility as in Rust.

An impl block holds associated constants (Vec2::ZERO), associated functions (Vec2::new) and methods. A method takes &self to read and &mut self to modify.

Enum variants can carry data, either as named fields (Circle { radius }) or as a tuple (Polygon(Vec<Vec2>)). match takes them apart, and | combines arms.

In compiled code, structs, enums and tuples live in the mod’s linear memory and are passed by value. An enum is stored as a tag, the variant’s index, followed by that variant’s fields.

02_structs_enums.ox

examples/syntax/02_structs_enums.ox
// Structs, enums and impl blocks.

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Vec2 {
    pub x: f32,
    pub y: f32,
}

impl Vec2 {
    pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };

    pub fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }

    pub fn length(&self) -> f32 {
        (self.x * self.x + self.y * self.y).sqrt()
    }

    pub fn scale(&mut self, factor: f32) {
        self.x *= factor;
        self.y *= factor;
    }
}

// Tuple and unit structs.
pub struct Meters(pub f32);
pub struct Marker;

// Enums carry data, like Rust's.
#[derive(Debug, Clone)]
pub enum Shape {
    Circle { radius: f32 },
    Rect { size: Vec2 },
    Polygon(Vec<Vec2>),
    Empty,
}

impl Shape {
    pub fn area(&self) -> f32 {
        match self {
            Shape::Circle { radius } => 3.14159 * radius * radius,
            Shape::Rect { size } => size.x * size.y,
            Shape::Polygon(_) | Shape::Empty => 0.0,
        }
    }
}

fn update_syntax() {
    let a = Vec2::new(1.0, 2.0);
    let b = Vec2 { y: 5.0, ..a };
}