zig

Constant struct fields in Zig


Dabbling with Zig and have a question about const fields in structs. In the simple struct below I have started to implement a simple matrix data structure. Presumably once I have instantiated a Matrix, the rows and columns fields will never change (and maybe this should be true for data too). However, my understanding is that Zig will only allow constant struct members if they are comptime. But there are many cases where the dimensions of my matrix will only be known at runtime (e.g. reading the data from a file) but should remain constant thereafter. Is there any way to enforce constness of the struct members?

pub const Matrix = struct {

    rows: u32,
    cols: u32,
    data: []const f32,

    /// Creates an uninitialized Matrix
    pub fn new(rows: u32, cols: u32) !Matrix {
        const data = try std.heap.page_allocator.alloc(f32, rows*cols);
        return Matrix{
            .rows = rows,
            .cols = cols,
            .data = data,
        };
    }

}

Solution

  • In Zig, individual struct fields cannot be made const.

    const can be applied to identifiers (variables), which means that all immediately addressed bytes are const. And pointers have their own constness. Also, function arguments are always const.

    Zig focuses on explicit memory management and mutability control through const identifiers and pointer types, rather than immutable data structures.