unlike container-level declarations (marked const
or var
), fields within a container don’t carry that distinction… and assuming these fields don’t appear within a packed
or extern
struct
, my understanding is that the compiler is free to locate them in any order it thinks best…
correct me if i’m wrong, but if my program effectively assigns a comptime
known value to a field – and if it’s not modified subsequently – the field’s value is propogated like any other const
… this field also appears to consume no runtime memory as well…
since all fields are public, i generally rely on methods to actually initialize and/or update these fields – enforcing my semantics of what is really mutable versus immutable…
assuming my clients don’t “cheat” and access fields directly (i’ll prefix field names with a leading “_
” as a convention), is this pattern something i can more or less rely upon???
things seem to be working out (beyond my expectations were i coming from C)… i just want to increase my understanding of the compiler a bit more…
Can you provide a scenario where you would be worried that it would fail? I think that would help us do some more direct detective work with ya.
it’s funny, because so far performance has exceeded my expectations!!!
but here’s a very trivial snippet of my “immutuable field” idiom:
const Thing = struct {
_data: u8,
pub fn getData(self: @This()) u8 {
return self._data;
}
};
if i then instantiate Thing{ ._data = 10 }
statically, i consume no additional .data
space in the final image; and calls to getData
on this instance fold away to the constant 10
…
were i to have a setData
method, the same initialized instance would consume some .data
space…
this technique appears to generalize, in that i can have some “readonly” properties and some “readwrite” properties by simply enforcing my semantics using getters and (optionally) setters…
my most important concern is the “readonly” case – which again has worked famously for me…
Yeah… tough call. I wonder if you’d run into the same issues that you’d get for referencing comptime var stuff though. I don’t know if the order of things would be maintained… might be.