Skip to content

Instantly share code, notes, and snippets.

@andrewrk
Created June 3, 2022 00:09
Show Gist options
  • Save andrewrk/a2612376de390aedee107be0464595b4 to your computer and use it in GitHub Desktop.
Save andrewrk/a2612376de390aedee107be0464595b4 to your computer and use it in GitHub Desktop.
a pattern using comptime fields that might be nice for applications that want to use a global allocator
const std = @import("std");
var gpa_instance: std.heap.GeneralPurposeAllocator(.{}) = .{};
const global_allocator = gpa_instance.allocator();
const S = struct {
comptime gpa: std.mem.Allocator = global_allocator,
x: i32,
};
pub fn main() !void {
defer _ = gpa_instance.deinit();
var s: S = .{ .x = 1234 };
try foo(&s);
}
fn foo(s: *S) !void {
const ptr = try s.gpa.create(i32);
defer s.gpa.destroy(ptr);
ptr.* = s.x;
s.x += 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment