Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Dynamic dispatch for zig made easy

License

NotificationsYou must be signed in to change notification settings

alexnask/interface.zig

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

See examples.zig for more examples.

About

Dynamic dispatch for zig made easy

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp