Files
spl/stage1/test16_methods.spl
2026-07-05 21:45:43 +08:00

49 lines
1.1 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* ===== 模块7高级特性 =====
* test16_methods — 类型关联方法
* 难度3/5
* 验证点struct 方法、enum 方法、self 参数自动填充、方法调用
*/
#[extern("vm")] fn vm_printf(fmt: *u8, ...) void;
type Point = struct {
x: i32,
y: i32,
fn init(x: i32, y: i32) Point {
ret Point { .x = x, .y = y };
}
fn dump(self: *Point) void {
vm_printf("Point(%d, %d)\n", self.x, self.y);
}
}
type Expr = enum {
Int: i32,
Add: struct { left: *Expr, right: *Expr },
fn eval(self: *Expr) i32 {
match self {
.Int(val) => ret val,
.Add(left, right) => ret eval(left) + eval(right),
}
ret 0;
}
}
fn main() i32 {
/* struct 方法调用 */
var p: Point = Point.init(3, 4);
p.dump();
/* enum 方法 + match */
var expr_l := Expr { .Int = 3 };
var expr_r := Expr { .Int = 4 };
var expr := Expr { .Add = { .left = expr_l, .right = expr_r } };
var result := expr.eval();
vm_printf("eval result: %d\n", result);
if result != 7 { ret 1; }
ret 0;
}