#author("2019-10-30T17:27:56+09:00","default:Miyashita","Miyashita")
#author("2019-10-30T17:29:11+09:00","default:Miyashita","Miyashita")
*構造体 Struct メモ [#d487b6ec]
#contents
**宣言の例 [#c24dcd60]
空間的な情報を入れる構造体を定義する例.
#codeprettify(lang-julia){{
mutable struct HogeType
    gridnumber::Int
    mx::Int
    my::Int
    Δx::Float64
    Δy::Float64
    η::AbstractArray{Float64, 2}
    # Constructor
    HogeType() = new()     
end
}}
データを読んで後から値を格納する場合は,struct の前に mutable をつける.~
end の前の行はコンストラクタを示しており,最も簡単な形式で書かれている.なくてもエラーにはならない.~
#codeprettify(lang-julia){{
var = HogeType()
var.mx = 50 # 代入の例.mutable struct でないとエラー
}}
コンストラクタに引数がないと,宣言した型に応じて勝手に何かの値が入る.
#codeprettify(lang-julia){{
var = HogeType()
println(var.mx)
 9
println(var.my)
 86023
}}
~

**プロパティ名が存在するか判定 [#u2a61d79]
function の内部で特定のプロパティ名があるか識別をしたいときなどに.
#codeprettify(lang-julia){{
isdefined(var,:mx)
 true
isdefined(var,:MX)
 false
}}
~

**構造体とabstract type [#b0d30821]
定義した構造体をグルーピングして,abstract typeのツリーにしたい場合は,先にabstract typeの名前を定義しておいて, 構造体の宣言時にその名前を使う.
#codeprettify(lang-julia){{
# abstract type 
abstract type AbstHoge end # <:T がない場合,<:Any 
# struct
mutable struct HogeType <: AbstHoge # ここで struct A <: B のようにする
    gridnumber::Int
    mx::Int
    my::Int
    Δx::Float64
    Δy::Float64
    η::AbstractArray{Float64, 2}
    # Constructor
    HogeType() = new()     
end
}}
~


**構造体から辞書型配列へ [#dc8ba690]
構造体の中身を展開し,Dict(:fieldname, value) の配列を作成する場合は下記の通り,
#codeprettify(lang-julia){{
struct2dict(x) = Dict(fn=>getfield(x, fn) for fn ∈ fieldnames(typeof(x)))
}}
これによって,例えば a[:mx]=10, a[:my]=20, なら,Dict(:a => 10, :b => 20) の辞書型の配列に変換できる.

参考ページは[[Convert type to dictionary>https://discourse.julialang.org/t/convert-type-to-dictionary/6982]].~
参考ページはここ→ [[Convert type to dictionary>https://discourse.julialang.org/t/convert-type-to-dictionary/6982]] .~
~


**構造体の配列を作成 [#cffeb8b4]
上述 HogeType の n 個作成したいときは,下記のどれかで宣言する.
#codeprettify(lang-julia){{
var = Array{HogeType}(undef,n)
var = Array{HogeType,1}(undef,n)
var = Vector{HogeType}(n)
}}
それぞれの要素で,HogeType 型として使える.
#codeprettify(lang-julia){{
var[1] = HogeType()
var[1].mx = 100
}}
さらに,n 個の配列( n は未定)を m 個作成するときは
&codeprettify(lang-julia){var = Vector{AbstractVector{HogeType}}(undef,m)};
となる. こうすると,HogeType[m][n] の形式で使える.~
~


**構造体配列からプロパティ値の取り出し [#d108bdde]
#codeprettify(lang-julia){{
var = HogeType()

}}
の構造体配列から,全要素の同じプロパティ(例えば mx )を抽出するときは,
#codeprettify(lang-julia){{
getfield.(var, :mx)
}}
とする.~
getfield(a, :mx) は a.mx と同値であるが,a が配列の場合は a.mx はエラーを返すため, getfield をブロードキャストする.map 関数を使っても良い.~
~

Front page   Edit Diff Attach Copy Rename Reload   New List of pages Search Recent changes   Help   RSS of recent changes