How to convert user-defined struct{T} to struct{Any} without redundant copy?

x = Int[1]
isimmuatble(x) # => false, so `===` performs comparing by reference, which checks if lhs and rsh are same.
x === convert(Vector{Any}, x) # => true 

What if I want to do such stuffs on custom structure

struct S{T} 
     a :: T # to avoid singleton, we need at least one field.
end

s = S{Int}(1)
convert(S{Any}, s) 

Which version are you using? That is impossible in any versions for any types AFAICT.

I’m sorry. Exactly I’m using v1.0.0.

Still, that’s impossible in any version on any types. The code you have (corrected for typo) doesn’t do what you claim it does, assuming you didn’t define any local names to change the meaning for any of the operations.

julia> x = Int[1]
1-element Array{Int64,1}:
 1

julia> isimmutable(x) # => false, so `===` performs comparing by reference, which checks if lhs and rsh are same.
false

julia> x === convert(Vector{Any}, x) # => true
false

@yuyichao Yes, I’ve just checked my julia history and found that I typed == instead of ===.

However are there anything like reinterpret_cast?

No. Julia is strongly typed and this is fundamentally impossible.

2 Likes

Is reinterpret_cast really fundamentally impossible for strong typed languages?

Depending on what you mean.
It’s impossible to cast a object to be treated as a different type. You can, however, cast between pointers in julia. In fact, every cast in C and C++ are still possible in julia, it’s just that pointers do not represent object.