Hi,
I have just discovered the catch with passing array slices to a function that is to modify the array entries. “view” is the solution. (9792).
The rub is, that while c[:,i] is a plain ol’ vector, view(c,:,i) has some complicated type. Logical enough, but throws a spanner in the works of my dispatch system.
function init!(a)
for i = 1:2
a[i] = 1. *i
end
end
function initstrict!(a::Vector{Float64})
for i = 1:2
a[i] = 1. *i
end
end
a = Array{Float64,1}(undef,2)
init!(a) # a is initialized
b = Array{Float64,1}(undef,2)
init!(b[:]) # deepcopy of b passed, b not initialised
c = Array{Float64,2}(undef,2,3)
init!(view(c,:,1)) # view to the rescue, 1st column initialised
c = Array{Float64,2}(undef,2,3)
initstrict!(view(c,:,1)) # uh oh, type mismatch!
I can workaround the issue with
c = Array{Float64,2}(undef,2,3)
a = Array{Float64,1}(undef,2)
initstrict!(a)
c[:,1] = a
but that’s a deepcopy and more code. I do not consider it an option to rewrite initstrict! to accept (“vectors or any vector-like view”).
There are other workarounds in my specific case, but I am here to learn: passing an array slice, easy method dispatching and no deepcopy? Yeah, can I have my slice and eat it?