Skip to content

Instantly share code, notes, and snippets.

@MasterQ32
Last active September 8, 2019 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MasterQ32/2408c0e20dde52d11d292176d0109424 to your computer and use it in GitHub Desktop.
Save MasterQ32/2408c0e20dde52d11d292176d0109424 to your computer and use it in GitHub Desktop.
Example for non-specializable interfaces
// some comments:
// this is not actual zig code (as it uses stuff not available in zig)
// it's an example used in a discussion about if "polymorphous interfaces" are required
// or if everything can be solved by specialization
const std = @import("std");
// interfaces are inherent "fat pointers"
// that store both vtable as well as a pointer to the object.
// also functions here omit the self field as the object type is not known at interface
// declaration time
/// this interface allows converting an object to or from a string value
const TextConvertible = interface {
fn toString(a:*Allocator) error{OutOfMemory}![]u8;
fn fromString(text : []u8) error{FormatError}!void;
};
/// Interface used in ui object
const Widget = interface { … };
/// A text box in the user interface that
/// allows having a value binding
const TextBox = struct {
value : ?TextConvertible, /// binding is refreshed when the user types in something
textBuffer : [256]u8,
};
const Point = struct {
x : i32,
y : i32,
implements TextConvertible;
// here the self argument is required
fn toString(pt : Point, a:*Allocator) error{OutOfMemory}![]u8 {
return std.format.string("x={}, y={}", pt.x, pt.y);
}
fn fromString(pt : Point, text : []u8) error{FormatError}!void {
std.format.parse("x={}, y={}", text, &pt.x, &pt.y) catch rerturn error.FormatError;
}
};
pub fn main() !void {
var ui = …;
var coords = Point { .x = 0, .y = 0 };
var coordinateBox = TextBox.create(TextConvertible(&upperCoords)); // casting a pointer to the interface creates a fat pointer
var nameBox = TextBox.create(TextConvertible(&lowerCoords));
ui.appendWidget(Widget(&coordinateBox));
ui.appendWidget(Widget(&nameBox));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment