Learn Aero / Structs · Enums · match

Structs · Enums · match

Structs

struct Point {
    x: i64,
    y: i64,
}

fn main() {
    let p = Point { x: 10, y: 20 };
    print(p.x + p.y);   // 30
}

Enums (Algebraic Data Types)

Enums can carry data; they are the foundation of Aero's error handling and optional values:

enum Maybe {
    Some(i64),
    None,
}

let a = Maybe::Some(42);
let b = Maybe::None;

match Pattern Matching

fn describe(v: Maybe) -> i64 {
    match v {
        Maybe::Some(x) => return x,
        Maybe::None => return -1,
    }
}

The built-in Option<T> (Some/None) and Result<T, E> (Ok/Err) are exactly such enums; see Error Handling for usage.

Methods with impl

Define methods in an impl block; the first parameter of the fn is Self:

impl Point {
    fn sum(self) -> i64 {
        return self.x + self.y;
    }
}

let p = Point { x: 1, y: 2 };
print(p.sum());   // 3

Copy / Drop Marker Traits

// 标记为 Copy 后按位拷贝而非移动
impl Copy for Point {}

// Drop(RAII):离开作用域时按声明逆序自动调用
impl Drop for Point {
    fn drop(x: &mut Self) {
        print("dropped\n");
    }
}
Aero 文档 · 基于 Aero 1.2.0 文档整理 · MIT
SereinTeam