#Best way to manage smaller memory scopes?

1 messages · Page 1 of 1 (latest)

woven junco
#

I need an array list for just a small chunk in the middle of a larger function;

Right now I have this:

    var scatter_plot: ScatterPlotData(f32) = undefined;
    {
        var array_list = std.ArrayList(f32).init(alloc);
        defer array_list.deinit();
        try getNumbersFromReader(buffered_reader, &array_list);
        scatter_plot = try ScatterPlotData(f32).init(alloc,array_list.items);
    }

I use {} to make a scope, then defer array_list.deinit();

But it seems clunky that in order to get scatter_plot defined outside of the block I need to assigne to undefined;

I tried const scatter_plot = {...} to use the block as an expression and assign the result, but AFAICT blocks are statements, not expressions.

What would be the idiomatic way to do this? Should it be a function that returns the scatter_plot? Or should I just let the memory live longer than it needs to?

light stirrup
#

The idiomatic way is const with a labeled block:

const scatter_plot: ScatterPlotData(f32) = scatter_blk: {
    var array_list = std.ArrayList(f32).init(alloc);
    defer array_list.deinit();
    try getNumbersFromReader(buffered_reader, &array_list);
    break :scattered_blk try ScatterPlotData(f32).init(alloc,array_list.items);
};
#

Apologies for formatting or if there's an error, I'm on mobile right now

woven junco
#

No worries, that works for me 🙂

#

Thanks for the help!