結構(Structs)

Julia 中級

Anthony Markham

Quantitative Developer

Structs - 簡介

  • 結構是複合型別的應用。
  • 與其他型別相似,但可包含任意多個欄位。
  • 先定義複合型別,再用它建立物件作為型別的具體表示。
Julia 中級

Structs - 語法

  • 使用關鍵字 struct 定義結構。
  • 結構內每個欄位在 struct 宣告中縮排。
struct Person
    age
    height
    location
end
steve = Person(18, 180, "London")
println(steve.height)
180
Julia 中級

Structs - 物件型別(typeof)

  • steve 的型別是 Person
struct Person
    age
    height
    location
end
steve = Person(18, 180, "London")
println(typeof(steve))
Person
Julia 中級

Structs - 不可變性示範

  • 結構預設為不可變。
# It's Steve's birthday!
steve = Person(18, 180, "London")
steve.age = 19
setfield!: immutable struct of type Person cannot be changed
Julia 中級

Structs - 可變結構

  • 使用關鍵字 mutable 建立可變結構。
mutable struct Person
    age
    height
    location
end
steve = Person(18, 180, "London")
steve.age = 19
println(steve)
Person(19, 180, "London")
Julia 中級

Structs - 指定型別的結構

  • 可在結構定義中為每個欄位指定資料型別。
mutable struct Person
    age::Int64
    height::Int64
    location::String
end
steve = Person(18.5, 180, "London")
InexactError: Int64(18.5)
Julia 中級

一起來練習吧!

Julia 中級

Preparing Video For Download...