Values & References14 / 18
Up next

Optional pointers

const std = @import("std");

// return a pointer to the first even, or null
fn firstEven(v: []i32) ?*i32 {
    for (v) |*e| {
        if (@rem(e.*, 2) == 0) return e;
    }
    return null;
}

pub fn main() void {
    var data = [_]i32{ 1, 3, 6, 7 };
    if (firstEven(&data)) |p| {
        p.* = -1;
    }
    std.debug.print("{any}\n", .{data});
}
What you're solving

?*T is null or a valid pointer