Hey y’all,
I’ve been looking through the documentation on structs, but I am struggling to understand fully the behavior of fields and specifically how they relate to instances versus the struct type. ZLS has guided me on a few restraints regarding field declaration (see below), but I am still a bit lost. Could someone point me towards some documentation I might’ve missed, or explain to me some of the behavior when it comes to fields? (Zig==0.11.0)
Declaration testing:
arr: [1]u8, // OK
arr: [1]u8 = undefined, // OK
comptime arr: [1]u8, // "error: comptime field without default..."
comptime arr: [1]u8 = undefined, // OK
arr: [1]u8; // "error: expected ',' after field..."
var arr: [1]u8 = undefined; // OK, but not accessible via the instance.
var arr: *[1]u8 = undefined, // Compiles, but causes segfault on assignment (e.g. arr.*[index] = value)
This question originates from a problem. In this scenario, I would ideally like a variable struct field;
fn Generic(comptime T, comptime a: i64) type {
return struct {
const Self = @This();
arr: [a]T = undefined;
fn new() Self { return .{}; }
fn set(s: Self, val: T, idx: usize) {
s.arr[idx] = val;
}
};
}
test {
const G1 = Generic(f32, 1);
const g1_inst = G1.new();
g1_inst.set(1.0, 0);
}
Yielding this error: error: cannot assign to a constant
.
Thanks!