Continuing my journey with Zig and interfaces, I have come into a situation where I am stuck.
Basically it seems trying to use comptime with vtable interfaces does not work?
To illustrate, this works
const LanguageInterface = struct {
// pointer to the logger object
ptr: *anyopaque,
speakFn: *const fn (ptr: *anyopaque, message: []const u8) void,
pub fn speak(self: LanguageInterface, message: []const u8) void {
return self.speakFn(self.ptr, message);
}
};
const SpanishInterface = struct {
pub fn language(self: *SpanishInterface) LanguageInterface {
return LanguageInterface{
.ptr = self,
.speakFn = speak,
};
}
pub fn speak(ptr: *anyopaque, message: []const u8) void {
const self: *SpanishInterface = @ptrCast(@alignCast(ptr));
_ = self;
std.debug.print("{s}", .{message});
}
};
pub fn main() !void {
var spanish = SpanishInterface{};
const language = spanish.language();
language.speak("hola");
}
But this does not work
const LanguageInterface = struct {
// pointer to the logger object
ptr: *anyopaque,
speakFn: *const fn (ptr: *anyopaque, comptime message: []const u8) void,
pub fn speak(self: LanguageInterface, comptime message: []const u8) void {
return self.speakFn(self.ptr, message);
}
};
const SpanishInterface = struct {
pub fn language(self: *SpanishInterface) LanguageInterface {
return LanguageInterface{
.ptr = self,
.speakFn = speak,
};
}
pub fn speak(ptr: *anyopaque, comptime message: []const u8) void {
const self: *SpanishInterface = @ptrCast(@alignCast(ptr));
_ = self;
std.debug.print("{s}", .{message});
}
};
pub fn main() !void {
var spanish = SpanishInterface{};
const language = spanish.language();
language.speak("hola");
}
It fails to compile with this error:
zig run src/main.zig
src/main.zig:35:29: error: unable to resolve comptime value
const language = spanish.language();
~~~~~~~^~~~~~~~~
src/main.zig:35:29: note: argument to function being called at comptime must be comptime-known
src/main.zig:18:46: note: expression is evaluated at comptime because the function returns a comptime-only type 'main.LanguageInterface'
pub fn language(self: *SpanishInterface) LanguageInterface {
^~~~~~~~~~~~~~~~~
src/main.zig:9:14: note: struct requires comptime because of this field
speakFn: *const fn (ptr: *anyopaque, comptime message: []const u8) void,
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/main.zig:9:14: note: function is generic
speakFn: *const fn (ptr: *anyopaque, comptime message: []const u8) void,
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How can I make it work?
Or maybe I am trying to do something that does not make sense and is not intended to work…ie using comptime in this way with vtable based polymorpishm can not work