basicaly I wanna write a function that takes any std.io.Reader as an argument, but I'm getting a error: expected type 'type', found 'fn(comptime type, comptime type, comptime anytype) type' error during compile which I assume is because generic types are just functions returning types in zig, and a function is not a type, so I don't know how to tell it to accept any reader
#how do I write functions with parameter of generic type?
1 messages · Page 1 of 1 (latest)
ATM, you do fn (reader: anytype) void { ... } then rely on duck-typing or try to verify it manually (which isnt as useful)
yeah I noticed that in the BufferedReader implementation but I was hoping there was something better like interfaces or soemthing instead of typescript-style manual type checking on any
one question: how do I verify it manually? cause trying to compare them with @typeInfo still results in a comparison of type with fn() type
I tried
if (@typeInfo(@TypeOf(in)) != std.io.Reader) @compileError(@typeName(in) ++ "is not a Reader");
``` but that didn't work
Reader is a function. By "verify it manually" you just check if all the signatures match that of reader. I say this isnt that useful as using the reader type implicit does this check for instances where it matters.
Without some way to uniquely tag structs generated by the reader fn (i.e. have it expose pub const this_is_a_reader_i_swear = true; then @hasDecl(T, "this_is...")) you cant do nominal subtyping
so basically I have to accept anytype as param and hope it works? would there be any compile errors if I pass a wrong struct or will it just panic at runtime?
if you do reader.read() on a struct withot that method, its a compile error. Think of fn (x: anytype) as fn(comptime T: type, x: T) so static type-checking still applies
ah, that makes sense, thanks a lot