Julia ---- fields 和 properties 的區別

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

 

發佈了94 篇原創文章 · 獲贊 74 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章