Created
May 14, 2024 14:50
-
-
Save shimamura-sakura/4cb998d744270993750068f036451ebe to your computer and use it in GitHub Desktop.
boxing a value in Zig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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