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,
    });
}


5 Likes

wow; I was working on this exact thing yesterday. I’m thinking about putting together a blog post about it because it was so much fun.

my use case is/was a little different. I am not trying to put together a reusable library, but instead discovering patterns to use as a runtime/compilation target for a toy language I am messing with that compiles to Zig. making it generalized into a library would have made it a lot harder!

there are a surprising number of capabilities built into Rust’s trait syntax, and you’ve got a lot of them implemented already, nice job. do you have any ideas about support for generic traits, blanket implementations, or any enhancements Rust doesn’t support?

2 Likes

I think using comptime should be able to simulate most of the capabilities of Rust traits. However, for my use case (where I want to use zig to create a multi-layer compiler framework similar to MLIR), the current functionality is sufficient. Nevertheless, I will expand this library as per my needs at any time.

1 Like

Would you be willing to add a license? I’d love to read your library, but it’s All Rights Reserved, and that would be unwise.

1 Like

Yes, the agreement is very important. The MIT open-source license has been added.

1 Like