I have an extern struct that must be passed to and from a consumer outside of my control. In C, this struct contains a field that is of type const int32_t, to denote that just this field within the struct should never be modified. However, I have no way to express the equivalent in Zig. Is there some other way I can denote that this field should never be mutated in some compiler-checked way?
#Struct `const` fields, or a way to `@compileError` on mutation
1 messages · Page 1 of 1 (latest)
not really. you can name it with a leading underscore or something and put a doc comment saying to not change it. you could hide it in like enum(i32) {_}. there's no way to mark a field as constant in zig though, only a pointer.
Yeah - in Zig, the mutability of the struct itself controls whether its fields are mutable.
Consider adding a doc-comment (///) to that field that says why you shouldn't mutate it.
Otherwise no bother
I am not sure if it will fit your use case @Mocha, but I was trying to do something along these lines today (which is how I found this thread) and had some success using a generic struct :
fn myGrid(comptime num_rows: u8, comptime num_cols: u8) type {
return struct {
data: [num_rows * num_cols]f32,
const Self = @This();
pub fn getItem(self: *const Self, i: u8, j: u8) f32 {
// the below would break if num_cols were modified, but it is comptime so that can't happen
return self.data[i * num_cols + j];
}
};
}
that doesn't stop you from modifying data tho