Search code examples
arraysstringslicezig

How to initialize a mutable array in Zig?


I've been working through ziglings, and in the last exercise (#107) I have to initialize a slice to a 64 character array filled with 'A's. This much is fine. The issue is that the values have to be mutable so I can read into it from a file.

I've tried this:

const content: []u8 = &[_]u8 {'A'} ** 64;

but I can't seem to generate the array as being mutable, and it errors with expected type '[]u8', but found'*const [64]u8' note: cast discards const qualifier

The only thing I've come up with that works is this mess:

var array: [64]u8 = undefined;
const content = array[0..array.len];
for (0..content.len) |i| {
    content[i] = 'A';
}

But the exercise seems to imply that there's a way of doing it in one line, using the ** operator to generate the array. Does anyone know how to do this? I've looked through the previous exercises, and the documentation, but I can't figure it out.


Solution

  • The exercise tells you to initialize an array, not a slice.

    You were close. The correct array initialization is as follows:

    var content = [_]u8{'A'} ** 64;
    

    You will also need to fix other lines in the file.