コンテンツにスキップ

エイリアス

alias を使用すると、型に別の名前を付けることができます。

alias PInt32 = Pointer(Int32)

ptr = PInt32.malloc(1) # : Pointer(Int32)

エイリアスを使用するたびに、コンパイラはそれを参照する型に置き換えます。

エイリアスは、長い型名を書くのを避けるのに役立ちますが、再帰的な型について話すこともできます。

alias RecArray = Array(Int32) | Array(RecArray)

ary = [] of RecArray
ary.push [1, 2, 3]
ary.push ary
ary # => [[1, 2, 3], [...]]

再帰型の実際の例はjsonです。

module Json
  alias Type = Nil |
               Bool |
               Int64 |
               Float64 |
               String |
               Array(Type) |
               Hash(String, Type)
end