Struct Field Documentation (0.11.0)

Comptime fields are kind of fake fields.
Normal fields just have a type and that type can be a u32, but you can’t define a const u32 field, because the const-ness is either via constants/variables or you can have a pointer to a constant, in that case it is a property of the pointer.

But you can sort of think of a field as constant if you have defined the instance as constant. For more info: Mutable and Constant Pointer Semantics

Can you rephrase what you mean with “what about the case when the struct instance is a variable?”


Just as a side-note:

Layout in Zig is often associated with field layout order and memory layout, so basically paddings between fields and so on, but that is relatively orthogonal to the whole concept of things being const.
Const is just a property on certain language constructs that is used to track whether something can/should be mutable, it doesn’t directly tell you whether something actually could be changed, it only helps you in avoiding mutating things that shouldn’t be mutated.

For example you can have a mutable memory region and within that a struct instance and you can have a mutable or a const pointer to that, with the former you can read and write to the memory, but with the latter you only can read the memory.

Now if you somehow know that the underlying memory is mutable, you can constCast the latter pointer to a mutable pointer and write to it anyway.

But now someone decided that you shouldn’t do that and used page mapping functions to set the memory to read only, now you can still const cast to get the mutable pointer, but the moment you write to it, you will get a segfault.

But now the former can’t write to it neither, but there is a whole wondrous rabbit hole, of interesting page mapping techniques, that I will have to explore with my own experiments in more detail some day. In this case page mapping could be used to map the same physical memory page at two different logical page addresses, where you set one to read only and the other to read/write.

Would be cool if that was some day optionally used in Zig to ensure that certain things aren’t modified, through for example pointers that shouldn’t be used to modify things.

But I don’t know enough about how safety checks are implemented, whether that would be one of the techniques there.