Hi All - New to Zig, and there are many things I can appreciate about it. I am looking at the following simple code, and trying to wrap my head around, how we are writing to a constconn. Isn’t writing to conn.stream mutating it? Doesn’t const imply immutability?
This might have been discussed before (and I looked at net.Stream.writeAll implementation), but I could not find a good explanation for this. Thanks in advance for your help.
If you look at the implementation of std.net.Stream.writeAll() you will see that the parameter self: Stream is passed by value (copied), so it doesn’t actually care about whether the original stream is mutable or not.
This works because Stream is just a wrapper around a socket_t which is a handle of a resource controlled by the OS (similiar to std.fs.File wrapping a fd_t) so the mutable state is not actually ‘part’ of your program:
This would be the case if std.net.Server.accept() returned a !*Connection, then the const would only affect the pointer and not to the Connection it points to.
But it returns a !Connection and const propagates recursively through containers so conn and all its fields (including conn.stream) are const here.
Thank you, I see that there are many peculiarities to be explored in this language. I must say that up to now I agree almost entirely with the choices made in its project, and this rarely happens, but undoubtedly many mechanisms I still have to study in depth.
Thank you, all, for your helpful comments. In addition to the items mentioned above, maybe something that I overlooked in the relationship between conn and listener is that conn.stream is based on listener.stream (which is initialized and owned by listener), and listener is declared as var. Hence the socket_t object that conn.stream.handle is pointing to is mutable.