Run-time Dynamic type-casting (RTTI)

Hello,
in ANSI C/C++, C#, Rust etc. there is MISSING this type of dynamic casting:

struct MyStruct { int item; };
MyStruct ms;
char dynTypeName[] = "MyStruct";
void *ptr;
ptr = &ms;
dynamic_cast<dynTypeName>(ptr)->item = 1; 

Ok, it would be very useful, but missing. And My question is:

Is there an equivalent of such dynamic run-time type-casting in Julia ?

Jerry

I guess this is meaningless in Julia, since Julia doesn’t have pointers (in normal use cases). You can directly use abstract types and cast it down to concrete type at runtime, just like in those dynamic languages. Example:

function f(x::Vector{Integer})
    for i in x
        if isa(i,Int)
            cast_i = i::Int
            println("is a Int")
        elseif isa(i,UInt8)
            cast_i = i::UInt8
            println("is a UInt8")
        end
    end
end
1 Like

ok, your aswer means, that the ::Vector can contain different types of variables. e.g.

x[0] is Int
x[1] is UInt8
x[2] is double
etc…

ok, thanks for reply …

It can only contain objects whose type is a subtype of Integer, so a double (Float64 in julia) would not be allowed.

2 Likes

“…a double ( Float64 in julia) would not be allowed…” ??? it is terrible …
I am very disappointed. :frowning:

Then you can use Vector{Number} or Vector{Any}. Any is the supertype of all the types, and Number is the supertype of all the number types (including double, int and complex). If you just want real number type, you can consider Real type.
P.S. It seems that you are unclear about Julia’s type system. You can read the Types section to get more info. Julia is quite different to those static-type languages like C#, C++ and go.

5 Likes

I’m not sure I understand why you’re disappointed? Surely you don’t expect floating point numbers to behave exactly like integers…? They’re very different things after all, both conceptually as well as how they’re represented in the computer. If you want a container that can hold a mixture of both while keeping their values, as has been said above, Vector{Real} or Vector{Any} are possibilities (or even Vector{Union{Integer, Float64}}, which can hold double precision floating points as well as any integer type like Int8, Int32 etc. but no other subtype of Real).

Additionally, you may not be aware that Integer is not the same as Int - the former is an abstract type in the type hierarchy, while the latter is a concrete type (a leaf that can’t be subtyped) in the type tree.

3 Likes

ok, thanks.