A zig library to emulate rust's trait

Inspired by zimpl library, I implemented a zig version(GitHub - passchaos/zigraft: trait power, grafted onto Zig · GitHub ) similar to rust’s trait, extending support for:

  • trait associated types
  • trait method default implementation
  • trait inheritance
  • trait projection.

The usage of this library is relatively simple. You can refer to tests.zig for the usage methods. For example, the following trait combination inheritance:

 pub fn Seekable(comptime T: type) type {
    return struct {
        const SeekError: type = zigraft.associatedType(T, "SeekError", zigraft.associatedType(T, "ReadError", anyerror));
        seekTo: fn (T, u64) SeekError!void,
    };
}

pub fn ReadSeek(comptime T: type) type {
    return zigraft.Compose(T, .{ Reader, Seekable }, struct {});
}

pub fn BufRead(comptime T: type) type {
    return zigraft.Compose(T, .{Reader}, struct {
        fillBuf: fn (T) anyerror![]const u8,
        consume: fn (T, usize) void,
    });
}

pub fn Stream(comptime T: type) type {
    return zigraft.Compose(T, .{ Named, ReadSeek, BufRead }, struct {
        describeAndRead: fn (T, []u8) anyerror!usize = struct {
            fn call(self: T, out: []u8) anyerror!usize {
                const impl = zigraft.Impl(Stream, T){};
                // std.debug.print("stream={s}\n", .{self.name});
                return impl.read(self, out);
            }
        }.call,
    });
}


1 Like