#Dynamically create and return array of length n

1 messages · Page 1 of 1 (latest)

bronze swallow
#

Imagine some code like this (note: the code comments are not valid Zig code)

fn createArray(num: u64) []u64 {
    var n = num;
    // var array: []64 = {};

    while (n > 0) : (n -= 1) {
      // array.append(n);
    }

    return array;
}

How can do something like this as efficiently as possible in Zig? I probably need ArrayList but then I would have to return an ArrayList instead of a slice and the ArrayList may be bigger than necessary because it may have some allocated but unused memory.

opal tundra
#

In this specific case, since you know the size of the array in advance, you could just do:

fn createArray(allocator: std.mem.Allocator, num: u64) ![]u64 {
    var array: []u64 = try allocator.alloc(u64, @intCast(usize, num));
    errdefer allocator.free(array);

    var index: u64 = 0;
    while (index < num) : (index += 1) {
        array[index] = num - index;
    }

    return array;
}
#

To specifically answer your ArrayList questions, you can use toOwnedSlice which is a shrink + move operation.

bronze swallow
#

That makes a lot of sense and was simpler than I thought. Thanks a lot for your help! @opal tundra