Card 1 / 12
Return the index of the first element equal to target, or null if not found.
Zig's optional type ?T represents "either a value of type T or null":
fn find(x: i32) ?usize {
return null; // not found
return 3; // found at index 3
}items |
target |
result | why |
|---|---|---|---|
[10, 20, 30, 40] |
30 |
2 |
found at index 2 |
[1, 2, 1, 2] |
2 |
1 |
the first match wins, not the later one |
[1, 2, 3] |
5 |
null |
no element equals the target |
[] |
1 |
null |
nothing to search |
Loop with for (items, 0..) |item, i| and return i when item == target.
/// Return the index of the first occurrence of target, or null
fn findFirst(items: []const i32, target: i32) ?usize {
for (items, 0..) |item, i| {
if (item == target) return i;
}
return null;
}Card 2 / 12
Division by zero is undefined. Signal the failure with an error set:
const DivError = error{DivisionByZero};