I also thought this was a good practice before:
This method is something I never thought of before. It’s great! If we adopt this approach, we don’t even need to introduce |T| grammar.
You can take a look at this example:
const std = @import("std");
pub fn satisfyTrait(comptime Trait: type, comptime T: type) R: {
if (@typeInfo(Trait) != .@"struct")
@compileError("Trait must be an 'struct'.");
break :R bool;
} {
const decls = std.meta.declarations(Trait);
inline for (decls) |decl| {
if (!std.meta.hasMethod(T, …
So I wrote a library for this purpose:
vftrait
A compile-time library for duck type checking.
URL: Verafahn/vftrait
idea from Discussion about |T: Trait| .I think this is a good practice, so I wrote this project.
This project implements a complete satisfyTrait function. After introducing it, you can define a trait (actually a struct) in the project to constrain anytype. I think this can also be considered as an implementation of compile time polymorphism.
satisfyTrait is not simply determining whether a type has the same members …
But when I actually used it for my code, I found that ZLS does not execute the comptime code at this location, which means I cannot directly trigger code completion after it. Meanwhile, Zig also does not allow shadows, which makes it very inconvenient to use.