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

65 lines
1.2 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.
/* ===== 模块5复合类型 =====
* test10_struct — 结构体
* 难度2/5
* 验证点struct 定义、字段访问、内联 type、嵌套结构体
*/
type Pair = struct {
a: i32,
b: i32,
}
fn main() i32 {
/* struct 字段访问 */
var p: Pair;
p.a = 1;
p.b = 2;
if p.a != 1 { ret 1; }
if p.b != 2 { ret 2; }
/* 同一类型复用 */
var p2: Pair;
p2.a = 10;
p2.b = 20;
if p2.a + p2.b != 30 { ret 3; }
/* 不影响其他实例 */
if p.a != 1 { ret 4; }
/* 内联 type 定义(在函数内) */
type Triple = struct {
x: i32,
y: i32,
z: i32,
}
var t: Triple;
t.x = 5;
t.y = 10;
t.z = 15;
if t.x + t.y + t.z != 30 { ret 5; }
/* 结构体字段运算 */
var calc: Pair;
calc.a = 7;
calc.b = 3;
var r := calc.a * calc.b + calc.a - calc.b;
if r != 25 { ret 6; }
/* 结构体嵌套 */
type Inner = struct {
val: i32,
}
type Outer = struct {
inner: Inner,
extra: i32,
}
var o: Outer;
o.inner.val = 42;
o.extra = 58;
if o.inner.val != 42 { ret 7; }
if o.extra != 58 { ret 8; }
ret 0;
}