Pass view to function



Suppose I define a new type

struct foo

and I create a vector

foos = [foo(3), foo(2), foo(9), foo(7)]

Now, I want a function that I could call as

bar(view(foos, 3:4))

or as

bar(view(foos, [2,4]))

or as

bar(view(foos, :)).

What is the best way to achieve that?


function bar(x)
  # x is the view

This auto-specializes on the type so there’s no performance left behind here.


Depends what you want to achieve. Possibly the best approach is to define bar(x::AbstractVector). If you want to restrict it to views specialize on SubArray. EDIT: of course if you don’t need to dispatch on the type you can just do what @ChrisRackauckas suggests above.


In fact, what I want to do is to use that function with an other type. So, I want something like

struct bar
    y::This is a view of a Vector{foo}

and to be able to call a constructor as I did in my original post.

Is it still a good idea to define it without specifying the type of y?



struct Bar{V <: AbstractVector{foo}}

which will let you create a Bar for any kind of vector of foo (including a regular Vector{foo} or a view into such a vector, etc.).


This is now different. Types should be strictly typed in order to get performance. You should do something like:

struct bar{T}

to leave it open but still get performance, or

struct bar{T<:AbstractArray}

etc. to place a check (note, there’s no performance difference though, it’s just a safety check).


Good, thank for the answer. That is exactly what I needed.