Reinterpret zero-dimensional view

Reinterpreting a zero-dimensional view:

a = [1; 2; 3]
b = view(a, 2)
c = reinterpret(UInt8, b) # ERROR: ArgumentError: cannot reinterpret a zero-dimensional `Int64` array to `UInt8` which is of a different size

The workaround is to add reshape:

a = [1; 2; 3]
b = view(a, 2)
c = reshape(b, 1)
d = reinterpret(UInt8, c)
#=
8-element reinterpret(UInt8, reshape(view(::Array{Int64,1}, 2), 1)):
 0x02
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
 0x00
=#
  1. Is there a better way than this to change how the compiler sees the type of a bunch of bits?
  2. If not, is there a reason reinterpret needs help to handle this?

Is this an alternative?

julia> b = view(a, 2:2)
1-element view(::Array{Int64,1}, 2:2) with eltype Int64:
 2
3 Likes

I guess that works, but my next question would be why there’s a difference in output between view(a, 2:2) and view(a, 2). Is there a point to a zero-dimensional view?

It’s the same as for ordinary slicing. a[2] is a scalar (as long as the eltype of a is), while a[2:2] is a vector. This is because 2 and 2:2 are of different types.

4 Likes

Yes, a 0-dimensional view is definitely sometimes useful, because it behaves just like the Ref type, but still refers to the original array. You can pass view(a, 2) to a function and that function can then modify the second entry of a with v[] = ..., where v is the name of the view. This can be useful for emulating the pass-by-reference behavior in C++, for example.

3 Likes

It’s an interesting case because reinterpret extends the first dimension to fit all the new elements… but there is no first dimension in a 0d array. I’ve often thought it’d be helpful for it to add a dimension instead, which would completely avoid this problem, but is of course breaking.

1 Like