Best practice to use lots of pre-allocated arrays in a function

This defines a new type with the name test. By default, its constructor creates an instance which holds a freshly-allocated vector

julia> @with_kw struct test
           u0::Vector{Float64} = zeros(5)
       end

This defines a function that accepts a callable and binds it to the name test within its body

julia> function f(test)
           @unpack u0 = test() # calls the `test` that is passed as argument
           u0 .= 2
       end

The defined function is called on a type constructor:

julia> f(test)

u0 within f is a freshly created array.

test() allocates a fresh array:

julia> test().u0

If you come from Python, you may have the impression that a mutable default argument for a function or a default mutable attribute for a class is created on function/class definition. In Julia, the default argument is an expression which is evaluated each time the function or constructor is called.

What @rdeits and @lmiq advised can be done as:

julia> @with_kw struct TestStruct
           u0::Vector{Float64} = zeros(5)
       end
test

julia> function f(test)
           @unpack u0 = test
           u0 .= 2
       end

julia> test_obj = TestStruct();

julia> f(test_obj)

julia> test_obj.u0
2 Likes