In your example you’re returning a slice to stack allocated memory. Instead, just return the entire array. Also you’re leaving some elements uninitialized. Maybe change the type to [max_size]?complex_struct
Thank you for the reply.
I don’t think I explained the issue well enough, though.
Sorry about that.
you’re leaving some elements uninitialized. Maybe change the type to [max_size]?complex_struct
I’m not trying to initialize an array of maybe-null values, I want to filter out the null values from something else that is mostly-null, leaving me with a much smaller array without null/undefined values.
I think the orelse continue; clause in the assignment should do that, since count isn’t incremented if maybeGetStruct() returns null?
If I’m wrong about that I think I may have misunderstood how orelse works.
The issue how you used orelse continue was just that you skipped initializing some items without storing which.
For example the function could return [a, b, undefined, c] and the consumer would have no way to know which items are bad data.
I’m assuming you only know how many items are null and need to be filtered at runtime - this means the size of the filtered array can only be known at runtime as well.
The easiest would be to allocate whatever space you need on the heap of course but if you don’t want to do that and the max_size isn’t too big, you could return a partially initialized array and a size of initialized values.
I think you missed that the loop variable and the array index aren’t the same variable.
I don’t need to store which are null if I’m only advancing the indexing variable when I store non-null things, which I am.
If max_size = 4 and maybeGetStruct would return [a, b, null, d] when looped over, they’d get loaded into the array as [a, b, d, undefined]. The final value of count is 3 and tmp[0..3] is [a, b, d].
Either way, I marked this solved. Something like BoundedArray was what I was looking for. Thank you both for the help.