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
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.
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 .
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.
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
Just a follow-on, you can get a tuple of all field types with fieldtypes
:
julia> fieldtypes(MyStruct)
(Int64, String)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With