(Julia 1.x) 获取 #undef 变量的类型



我希望获取struct中的字段类型,以便相应地设置字段值。某些数据类型在实例化时初始化值(例如 Int64Float64 (,而其他类型初始化为 #undef (例如 StringArray(。虽然typeof(getfield())适用于前一种类型,但它对后者UndefRefError

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

有没有办法获取未初始化变量的类型,或者#undef指示明显缺乏类型?或者,是否可以使用内部构造函数初始化默认值?例如

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

您正在寻找fieldtype函数:

julia> fieldtype(MyStruct, :a)
Int64                         
julia> fieldtype(MyStruct, :b)
String                        

对于您的另一个问题,您当然可以初始化字段。

mutable struct MyStruct
    a::Int64
    b::String
    MyStruct() = new(0,"") # will initialize a as 0 and b as ""
end

只是后续,您可以使用fieldtypes获得所有字段类型的元组:

julia> fieldtypes(MyStruct)
(Int64, String)

最新更新