fields 只是一個結構體的一個字段
struct A
b
c::Int
end
結構體A有兩個字段:b,c,這時候可以用getfield 獲取結構體實例的字段,如:
a = A("foo", 3)
getfield(a, :b)
在早期版本中 通過a.b 下標的方式獲取字段,這與getfield(a, :b) 作用是一樣的,現在情況是
a.b 與getproperty(a, :b) 默認是一致的。
getproperty(a::Type, v::Symbol) = getfield(a, v)
其實沒有太多變化,但是用戶可以通過重載getproperty()來實現額外的功能,但是不能通過重載getfield(a, v)
代碼樣例
struct A
b
c::Int
end
a = A("foo", 3)
getfield(a, :b)
function Base.getproperty(a::A, v::Symbol)
if v == :c
return getfield(a, :c) * 2
elseif v == :q
return "q"
else
return getfield(a, v)
end
end
a.q
#"q"
getfield(a, :q) #會報異常
#type A has no field q
#top-level scope at struct:21
a.c
#6