Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Julia 1.x) Getting type of #undef variable

Tags:

julia

I am looking to get the types of the fields within a struct in order to set the field values correspondingly. Some data types initialise values on instantiation (e.g. Int64, Float64), whereas other types initialise to #undef (e.g. String, Array). Whilst typeof(getfield()) works for the former types, it throws UndefRefError for the latter:

julia> mutable struct MyStruct
           a::Int64
           b::String
           MyStruct() = new()
       end

julia> foo = MyStruct()
MyStruct(0, #undef)

julia> typeof(getfield(foo, :a))
Int64

julia> typeof(getfield(foo, :b))
ERROR: UndefRefError: access to undefined reference
Stacktrace:
 [1] top-level scope at none:0

Is there is way to get the type of an uninitialised variable or does #undef indicate the distinct lack of a type? Alternatively, is it possible to initialise default values using the inner constructor? e.g.

julia> mutable struct MyStruct
           a::Int64
           b::String
           MyStruct() = new(b = "")
       end
like image 241
DocDave Avatar asked Aug 07 '19 10:08

DocDave


People also ask

What is the type of a function in Julia?

Method Tables Every function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table.

What is :: In Julia?

A return type can be specified in the function declaration using the :: operator. This converts the return value to the specified type. This function will always return an Int8 regardless of the types of x and y .

What makes Julia unique?

Julia gives the functionality of multiple dispatch. It will be explained in detail in coming chapters. Multiple dispatch refers to using many combinations of argument types to define function behaviors. Julia provides efficient, specialized, and automatic generation of code for different argument types.


2 Answers

You're looking for the fieldtype function:

julia> fieldtype(MyStruct, :a)
Int64                         

julia> fieldtype(MyStruct, :b)
String                        

To your other question, you surely can initialize fields.

mutable struct MyStruct
    a::Int64
    b::String
    MyStruct() = new(0,"") # will initialize a as 0 and b as ""
end
like image 101
carstenbauer Avatar answered Oct 01 '22 02:10

carstenbauer


Just a follow-on, you can get a tuple of all field types with fieldtypes:

julia> fieldtypes(MyStruct)
(Int64, String)
like image 44
Engineero Avatar answered Oct 01 '22 03:10

Engineero