3vilRat
3vilRat

Reputation: 3

How to make array members variable?

I get this error while trying to build: suds.zig:29:26: error: cannot assign to constant This is my code:

const std = @import("std");

const SIZE: u8 = 9;

fn create_board() [SIZE][SIZE]u8 {
    var board: [SIZE][SIZE]u8 = undefined;
    for (&board) |*row| {
        row.* = [_]u8{0} ** 9;
    }
    return board;
}

pub fn main() !void {

    const halloc = std.heap.page_allocator;
    var board = create_board();

    for (board, 0..) |row, r| {
        for (row, 0..) |field, c| {
            while (true) {
                std.io.getStdOut().writer().print("Enter number for row {}, column {} - '0' if empty: ", .{r, c}) catch @panic("Output error!");
                const field_input = std.io.getStdIn().reader().readUntilDelimiterAlloc(halloc, '\n', 4) catch @panic("Input error!");
                defer halloc.free(field_input);
                const parse_input = std.fmt.parseInt(u8, field_input, 10) catch {
                    std.io.getStdOut().writer().print("\nInvalid integer, try again.\n", .{}) catch @panic("Output error!");
                    continue;
                };
                if (parse_input <= SIZE) {
                    field = parse_input;
                    break;
                } else {
                    std.io.getStdOut().writer().print("\nValue too large, try again.\n", .{}) catch @panic("Output error!");
                    continue;
                }
                
            }
        }
    }

}

So I cannot assign anything to field because it was declared as constant apparently. How do I declare it as variable?

Changing it to pointers (for (&row, 0..) |*field, c| {) yields the same result.

Upvotes: 0

Views: 146

Answers (1)

sigod
sigod

Reputation: 6397

The capture values in for loops are implicitly marked as const. (I don't see this mentioned in the docs, though. Perhaps the rule that function parameters are immutable also applies to capture values.)

This means that row is const, which is passed to field, which becomes const *const u8 instead of const *u8. You can work around this by declaring the row separately.

for (0..board.len) |r| {
    var row = &board[r];
    for (row, 0..) |*field, c| {
        // ...

        field.* = parse_input;
    }
}

Upvotes: 3

Related Questions