Structs & Enums — Mapanare
Product types and sum types — algebraic data types with no classes or inheritance.
Structs
struct Point { x: Float, y: Float }
struct User { name: String, age: Int, active: Bool }
Impl Blocks
Methods are defined in separate impl blocks. Use self to access the instance. Functions without self are static methods.
impl Point {
fn distance(self, other: Point) -> Float {
let dx = self.x - other.x
let dy = self.y - other.y
return Math::sqrt(dx * dx + dy * dy)
}
fn origin() -> Point { return Point(0.0, 0.0) }
}
Enums
Enums are sum types. Each variant can carry associated data:
enum Shape { Circle(Float), Rectangle(Float, Float), Triangle(Float, Float, Float) }
fn area(shape: Shape) -> Float {
match shape {
Circle(r) => 3.14159 * r * r,
Rectangle(w, h) => w * h,
Triangle(a, b, c) => { let s = (a+b+c)/2.0; return Math::sqrt(s*(s-a)*(s-b)*(s-c)) },
}
}
Generic Enums
The built-in Option<T> and Result<T, E> types are generic enums: Option has Some(T) and None; Result has Ok(T) and Err(E).
Visibility
Structs and enums can be marked pub to export them from their module.