Hey guys, I have a Diag union enum which holds some information about various errors that has appeared during the execution. I want one of the variants to hold an array of "expected" values. What would be the best way of doing that type-wise without allocations? I currently do unexpected_type: [3]?TypeIndex where I can have up to three values, in case I only have 2 values, then the third elem will be null, if only one then the last 2 will be null. This works well, but it's kind of a pain in the ass to add trailing nulls like .{expected_index, null, null} . Especially when I have large arrays. Is there a way to give a default element value to the array? So that if I do .{expected_index} it will initialize the array with only the first index being set and the rest with nulls. I know that I can do it in two expressions but I'm wondering if it's possible to do just in the initializer
#Idiomatic way to initialize arrays of nullable elems
1 messages · Page 1 of 1 (latest)
With a comptime function?
const std = @import("std");
fn initFromTuple(x: anytype) [3]?u64 {
var out: [3]?u64 = @splat(null);
if (x.len > 3) @compileError("Too many");
inline for (x, 0..) |v, i| {
out[i] = v;
}
return out;
}
pub fn main() !void {
const arr: [3]?u64 = initFromTuple(.{ 64, 65 });
std.debug.print("{any}\n", .{arr});
const slc = std.mem.sliceTo(&arr, null);
std.debug.print("{any}\n", .{slc});
}
// Define Diag somewhere
pub fn main !void {
const count = 5; // determines the length of the array
const arr = [_]?Diag{null} ** count;
}