#how do I write functions with parameter of generic type?

1 messages · Page 1 of 1 (latest)

tulip glade
#

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

pale sail
#

ATM, you do fn (reader: anytype) void { ... } then rely on duck-typing or try to verify it manually (which isnt as useful)

tulip glade
#

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

tulip glade
pale sail
#

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

tulip glade
#

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?

pale sail
#

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

tulip glade
#

ah, that makes sense, thanks a lot