There are two ways:
- allocator as function parameter
pub fn insert(self: *Self, allocator: std.mem.Allocator, word: []const u8) !void {
...
var new_node = try allocator.create(TrieNode);
...
}
- allocator as member
const Trie = struct {
allocator: std.mem.Allocator,
...
}
pub fn insert(self: *Self, word: []const u8) !void {
...
var new_node = try self.allocator.create(TrieNode);
...
}
To get the allocator:
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
For each allocator.create you need an allocator.destroy to free memory.
A great allocator tutorial is: Learning Zig - Heap Memory & Allocators
Also note: Allocation is not Initialization