zig icon indicating copy to clipboard operation
zig copied to clipboard

Proposal: std.interface - better polymorphism support in standard library

Open iacore opened this issue 4 years ago • 7 comments

For new language users from languages with language-level polymorphism support, it's not clear how to achieve polymorphism in Zig. I think it's important in include an easy way to create new type classes in the standard library for discoverability. The implementation for owned and not-owned type classes already exists as a third-party library. We just need to put it in the standard library and use it within std too (e.g. mem.Allocator).

Related issues: #130, #1268, #4567, #9272

iacore avatar Nov 20 '21 15:11 iacore

std.io.Writer needs this feature. Currently I have to write writer: anytype, which is not ideal.

iacore avatar Dec 31 '21 09:12 iacore

I think I'm leaning more towards taking advantage of compile time duck typing for interfaces. Less complications and side issues. What would be better IMO is addition of "@InterfaceOf(interface: type)" builtin which would work exactly like anytype except it would throw a compile error if you passed in anything that wouldn't match the interface type or if you tried to use within the function that uses the interface what isn't declared on it. I think that would be better in terms of not adding unnecessary complexity to the language, take advantage of what's already there and provide additional type safety for both function/library user and writer. Something like this is already emerging in standard library, for example in HashMap's Context or crypto.tls.Client Stream interfaces.

purrie avatar Jul 21 '23 12:07 purrie

I believe the std reader and writer have been restructured now to be proper interfaces

VisenDev avatar Feb 24 '24 18:02 VisenDev

I believe the std reader and writer have been restructured now to be proper interfaces

What are the 'proper interfaces' you mention? Zig doesn't have interfaces.

WizardUli avatar Feb 24 '24 19:02 WizardUli

What are the 'proper interfaces' you mention?

Interfaces meaning a struct containing a *anyopaque and a function pointer. This is how std.mem.Allocator is implemented.

Zig now has a proper interface for Reader and Writer methods, rather than using comptime duck typing. The old reader and writers have been deprecated

VisenDev avatar Feb 24 '24 20:02 VisenDev

@VisenDev Your link doesn't return any result, did you mean https://ziglang.org/documentation/master/std/#std.io.AnyReader?

dgellow avatar Apr 15 '24 11:04 dgellow

@VisenDev Your link doesn't return any result, did you mean https://ziglang.org/documentation/master/std/#std.io.AnyReader?

Zig recently changed the autodoc code. That must have broken my link

VisenDev avatar Apr 15 '24 14:04 VisenDev