You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Easy solution for all your zig dynamic dispatch needs!
Features
Fully decoupled interfaces and implementations
Control over the storage/ownership of interface objects
Comptime support (including comptime-only interfaces)
Async function partial support (blocking on #4621)
Optional function support
Support for manually written vtables
Example
constinterface=@import("interface.zig");
constInterface=interface.Interface;
constSelfType=interface.SelfType;
// Let us create a Reader interface.// We wrap it in our own struct to make function calls more natural.constReader=struct {
pubconstReadError=error { CouldNotRead };
constIFace=Interface(struct {
// Our interface requires a single non optional, non-const read function.read: fn (*SelfType, buf: []u8) ReadError!usize,
}, interface.Storage.NonOwning); // This is a non owning interface, similar to Rust dyn traits.iface: IFace,
// Wrap the interface's init, since the interface is non owning it requires no allocator argument.pubfninit(impl_ptr: var) Reader {
return .{ .iface=tryIFace.init(.{impl_ptr}) };
}
// Wrap the read function callpubfnread(self: *Reader, buf: []u8) ReadError!usize {
returnself.iface.call("read", .{buf});
}
// Define additional, non-dynamic functions!pubfnreadAll(self: *Self, buf: []u8) ReadError!usize {
varindex: usize=0;
while (index!=buf.len) {
constpartial_amt=tryself.read(buffer[index..]);
if (partial_amt==0) returnindex;
index+=partial_amt;
}
returnindex;
}
};
// Let's create an example readerconstExampleReader=struct {
state: u8,
// Note that this reader cannot return an error, the return type// of our implementation functions only needs to coerce to the// interface's function return type.pubfnread(self: ExampleReader, buf: []u8) usize {
for (buf) |*c| {
c.*=self.state;
}
returnbuf.len;
}
};
test"Use our reader interface!" {
varexample_reader=ExampleReader{ .state=42 };
varreader=Reader.init(&example_reader);
varbuf: [100]u8=undefined;
_=reader.read(&buf) catchunreachable;
}