Escaping structs with heap-allocated elements will also be heap allocated.
In the case of multiple return values, that means the tuple you’re constructing (the one holding all the returned values) must be heap allocated.
Given that you’re already preallocating, two options are:
Don’t return the preallocated object. The caller must already have access to it.
Preallocate objects with space for all the returned values, eg
mutable struct ArrayAndInt{T}
x::Array{T}
i::Int
end
then pass a preallocated instance, mutating i, and returning.
I’ve run into the same issue a few times. Although there are of multiple workarounds they nine are elegant. It would be very nice to have this fixed at the language level.
Most of the time the allocation doesn’t matter and one can just ignore it but occasionally it does make a difference. (And also for the typical “obsessive-compulsive” academic it is good for peace of mind to have zero allocations.)