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

44 lines
1.1 KiB
Plaintext
Raw Permalink 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复合类型 =====
* test09_slices — 切片
* 难度2/5
* 验证点arr[begin..end] 创建切片、arr[begin..] 到末尾、
* 切片索引访问、slice.len、slice.ptr
*/
fn main() i32 {
/* 从数组创建切片 */
var arr: [5]i32 = [5]i32{10, 20, 30, 40, 50};
var slice: []i32 = arr[1..4];
/* 切片长度 */
if slice.len != 3 { ret 1; }
/* 切片元素访问 */
if slice[0] != 20 { ret 2; }
if slice[1] != 30 { ret 3; }
if slice[2] != 40 { ret 4; }
/* 省略结束值arr[begin..] */
var full: []i32 = arr[0..];
if full.len != 5 { ret 5; }
if full[0] != 10 { ret 6; }
if full[4] != 50 { ret 7; }
/* 从开头到中间 */
var head: []i32 = arr[0..3];
if head.len != 3 { ret 8; }
if head[0] != 10 { ret 9; }
/* 切片遍历(配合 for*/
var nums: [3]i32 = [3]i32{100, 200, 300};
var sl: []i32 = nums[0..];
var total: i32 = 0;
var i: i32 = 0;
while i < sl.len {
total = total + sl[i];
i = i + 1;
}
if total != 600 { ret 10; }
ret 0;
}