Last active
February 4, 2025 03:42
-
-
Save abradley2/5cd9b6d4f142b91a6fdb89fd0c78c7e7 to your computer and use it in GitHub Desktop.
You don't need interfaces in Zig
This file contains hidden or 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"); | |
fn Writer(comptime T: anytype) type { | |
return struct { Write: fn (t: *T, b: []const u8) anyerror!usize }; | |
} | |
fn writeHello(comptime T: anytype, comptime writer: Writer(T), t: *T) anyerror!usize { | |
return writer.Write(t, "Hello there"); | |
} | |
fn writeArrayList(t: *std.ArrayList(u8), b: []const u8) anyerror!usize { | |
try t.appendSlice(b); | |
return b.len; | |
} | |
fn writeByteSlice(t: *[]u8, b: []const u8) anyerror!usize { | |
@memcpy(t.*[0..b.len], b); | |
return b.len; | |
} | |
pub fn main() anyerror!void { | |
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); | |
defer arena.deinit(); | |
var al = std.ArrayList(u8).init(arena.allocator()); | |
_ = try writeHello(std.ArrayList(u8), Writer(std.ArrayList(u8)){ .Write = writeArrayList }, &al); | |
std.debug.print("Result: {s}\n", .{al.items}); | |
var bs: []u8 = try arena.allocator().alloc(u8, 64); | |
const len = try writeHello([]u8, Writer([]u8){ .Write = writeByteSlice }, &bs); | |
std.debug.print("Result: {s}\n", .{bs[0..len]}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment