Help me understand some of `io.zig` in the standard library

Ok, new to Zig, maybee too soon for me to be skimming the standard library code, but there isn’t much documentation. (Not a complaint - I know it is a new language, and frankly, the code almost looks understandable to me at this point, which is sort of amazing to me).

So, fn GenericWriter defines a structure in it’s body, and returns it (which is cool). There are a few functions defined in the structure, such as writeStructEndian that have bodies like: return @errorCast(self.any().writeStructEndian(value, endian));.

So, the any function in the struct, also returns an anonymous struct having fields: .context and .writeFn … so here’s my confusion: in following self.any(), I’m assuming that writeStructureEndian is then called on the anonymous structure? How does that work? The anonymous structure doesn’t define that function and Zig doesn’t have inheritance?

The anyonymous struct literal creates an instance with the type of the return type of the any function and the return type has the writeStructureEndian method.

So, the anonymous constructor serves to fill in default values for an AnyWriter struct (which does have a writeStructureEndian` method)?

If so, I guess I wasn’t catching that the anon struct was used like that.

In Zig every value has a type, anonymous structs literals just allow you to have that type be inferred based on the type of the result location.

Zig doesn’t have constructors.

No default values, but it creates a struct instance of type AnyWriter with specific values, yes.

AnyWriter is declared as:

pub const AnyWriter = @import("io/Writer.zig");

And this imports the #src/std/io/Writer.zig struct.

related:

4 Likes

FWIW, I think it’s a little hard to follow what’s going on with this when browsing through these types via the standard library reference docs.

I always read the std source directly instead.