Card 1 / 11
Slices in Zig are a pointer + length pair. []const i32 is a slice of immutable i32 values.
Iterate over a slice with for:
for (items) |item| {
// use item
}items |
result |
|---|---|
[1, 2, 3, 4] |
10 |
[-1, 1, -2, 2] |
0 |
[42] |
42 |
[] |
0 |
Accumulate into a var sum: i32 = 0 and add each element.
/// Return the sum of all elements in the slice
fn sum(items: []const i32) i32 {
var total: i32 = 0;
for (items) |item| {
total += item;
}
return total;
}Card 2 / 11
Find the maximum value in a slice. The return type is ?i32: it contains the maximum for a non-empty slice and is null when no value exists.
An early empty check lets the running maximum itself remain a plain i32: