julia - (Julia 1.x) 获取#undef 变量的类型
问题描述
我希望获取 astruct
中字段的类型,以便相应地设置字段值。一些数据类型在实例化时初始化值(例如Int64
, Float64
),而其他类型初始化为#undef
(例如String
, Array
)。虽然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