Skip to content

Instantly share code, notes, and snippets.

@shimamura-sakura
Created May 14, 2024 14:50
Show Gist options
  • Save shimamura-sakura/4cb998d744270993750068f036451ebe to your computer and use it in GitHub Desktop.
Save shimamura-sakura/4cb998d744270993750068f036451ebe to your computer and use it in GitHub Desktop.
boxing a value in Zig
const std = @import("std");
const Allocator = std.mem.Allocator;
pub fn box(allocator: Allocator, value: anytype) !*@TypeOf(value) {
const ptr = try allocator.create(@TypeOf(value));
ptr.* = value;
return ptr;
}
test {
const a = std.testing.allocator;
const p = try box(a, @as(u32, 12345));
defer a.destroy(p);
try std.testing.expectEqual(12345, p.*);
p.* = 67890;
try std.testing.expectEqual(67890, p.*);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment