Skip to content

Optional

Chung Leong edited this page Feb 15, 2024 · 3 revisions

Optional is a Zig data structure for holding values that are sometimes absent. When using Zigar, you generally won't encounter standalone optional objects. Upon access they're automatically resolved to their assigned values or null.

pub fn findIndex(haystack: []const u8, needle: [1]u8) ?usize {
    var index: usize = 0;
    while (index < haystack.len) : (index += 1) {
        if (haystack[index] == needle[0]) {
            return index;
        }
    }
    return null;
}
import { findIndex } from './optional-example-1.zig';

const text = 'Hello world';
console.log(findIndex(text, 'w'));
console.log(findIndex(text, 'z'));
6
null
Clone this wiki locally