Returning Arrays from Functions - Recommended Approach?

I have been working through an exercise of reviewing and re-reviewing some code I have that solves a one-dimensional system of coupled ODEs using finite differences (just as a toy problem to get better with Julia). I have managed to squeeze every single allocation out of the loops of my calculations by using mutating functions, generators, and pre-allocated arrays.

Presently, all the code is in a single function (called solve). I think it would be better to re-organize that code into functions within solve() instead of being one monolithic chunk of code.

The problem I have is that I need to pre-allocate 13 arrays of various size. If I were to move all the pre-allocation code into a function (e.g. setup()), something like the pseudo code below, I don’t know what the best way to return a bunch of variably sized arrays from a function is. As a tuple of functions? Create a struct where each field is one of the arrays and return that?

Hopefully my question makes sense. Perhaps I am over complicating it but I would appreciate any advice or thoughts on how to accomplish this.

function solve()
pre_allocated_arrays = setup() # <- calling the setup function to generate pre-allocated arrays
# Hot loop

I usually use a struct of arrays that I pass to every function as first parameter, because in this way it can be re-used for multiple calls to solve() and is allocated only once. You can see a complex example here: KiteModels.jl/KiteModels.jl at main · ufechner7/KiteModels.jl · GitHub line 107ff

I usually have functions like:

As long as there are only arrays in the struct there is no need for a mutable struct, a simple (immutable) struct is good enough.


Thanks for the example. I implemented your approach - I have an init function that generates the struct containing all the arrays then I pass it to my solve function which has the hot loop. Thank you!

You are welcome!