Null represents the absence of a valid pointed-to object. Zig makes nullability explicit in types and checks it, helping prevent nullable C values from reaching code that does not expect them. section 1.2.1
At C boundaries, nullable pointers can signal failure: creating a recipe book returns an optional pointer that is null if allocation fails. Loading returns null for file-open, allocation, or deserialization failures, so callers should check before use. section 5.3.1 section 5.4.3
Null is compact but gives little information about why something failed. Error codes can distinguish causes, such as running out of memory or requesting an invalid recipe ID. section 5.4.1
When using GLFW, pointer-returning functions use C NULL to indicate errors; check these values manually for reliable Zig code. section 7.3.1
Listing 5.3 An object without methods
const std = @import("std");
var gpa: std.heap.SafeAllocator(.{}) = .init; #1
var threaded: std.Io.Threaded = .init_single_threaded;
export fn recipes_quit() void {
_ = gpa.deinit(); #2
threaded.deinit();
gpa = .init; #3
threaded = .init_single_threaded;
}
const RecipeBook = struct {}; #4
export fn recipe_book_create() ?*RecipeBook { #5
const ally = gpa.allocator();
const book = ally.create(RecipeBook) catch {
return null; #6
};
book.* = .{}; #7
return book;
}
export fn recipe_book_close(book: *RecipeBook) void { #8
const ally = gpa.allocator();
book.deinit(ally); #9
ally.destroy(book);
}
See an exported creation function return ?*RecipeBook and return null when allocation fails. section 5.3.1
