コンテンツにスキップ

型文法

以下の場合に

いくつかの一般的な型に便利な構文が用意されています。これらはC言語バインディングを書くときに特に便利ですが、上記のどの場所でも使用できます。

パスとジェネリクス

通常の型とジェネリクスを使用できます

Int32
My::Nested::Type
Array(String)

共用体(Union)

alias Int32OrString = Int32 | String

型におけるパイプ記号(|)は共用体型を作成します。 Int32 | String は「Int32またはString」と読みます。通常のコードでは、`Int32 | String` は `Int32` に対して `String` を引数として `|` メソッドを呼び出すことを意味します。

Nilable(Null許容)

alias Int32OrNil = Int32?

は以下と同じです

alias Int32OrNil = Int32 | ::Nil

通常のコードでは、`Int32?` はそれ自体 `Int32 | ::Nil` 共用体型です。

ポインタ

alias Int32Ptr = Int32*

は以下と同じです

alias Int32Ptr = Pointer(Int32)

通常のコードでは、`Int32*` は `Int32` に対して `*` メソッドを呼び出すことを意味します。

StaticArray(静的配列)

alias Int32_8 = Int32[8]

は以下と同じです

alias Int32_8 = StaticArray(Int32, 8)

通常のコードでは、`Int32[8]` は `Int32` に対して `8` を引数として `[]` メソッドを呼び出すことを意味します。

タプル

alias Int32StringTuple = {Int32, String}

は以下と同じです

alias Int32StringTuple = Tuple(Int32, String)

通常のコードでは、`{Int32, String}` は `Int32` と `String` を要素として含むタプルの**インスタンス**です。これは上記のタプル**型**とは異なります。

名前付きタプル

alias Int32StringNamedTuple = {x: Int32, y: String}

は以下と同じです

alias Int32StringNamedTuple = NamedTuple(x: Int32, y: String)

通常のコードでは、`{x: Int32, y: String}` は `x` と `y` に `Int32` と `String` を含む名前付きタプルの**インスタンス**です。これは上記のタプル**型**とは異なります。

Proc

alias Int32ToString = Int32 -> String

は以下と同じです

alias Int32ToString = Proc(Int32, String)

パラメータのないProcを指定するには

alias ProcThatReturnsInt32 = -> Int32

複数のパラメータを指定するには

alias Int32AndCharToString = Int32, Char -> String

ネストされたproc(および一般的にあらゆる型)の場合、括弧を使用できます

alias ComplexProc = (Int32 -> Int32) -> String

通常のコードでは `Int32 -> String` は構文エラーです。

self

型文法では `self` を使用して `self` 型を表すことができます。型制約セクションを参照してください。

class

`class` は、インスタンスタイプではなく、クラス型を参照するために使用されます。

例えば

def foo(x : Int32)
  "instance"
end

def foo(x : Int32.class)
  "class"
end

foo 1     # "instance"
foo Int32 # "class"

`class` は、クラス型の配列やコレクションを作成するのにも役立ちます

class Parent
end

class Child1 < Parent
end

class Child2 < Parent
end

ary = [] of Parent.class
ary << Child1
ary << Child2

アンダースコア

型制約ではアンダースコアが許可されています。これは何でも一致します

# Same as not specifying a restriction, not very useful
def foo(x : _)
end

# A bit more useful: any two-parameter Proc that returns an Int32:
def foo(x : _, _ -> Int32)
end

通常のコードでは、`_` はアンダースコア変数を意味します。

typeof

型文法では `typeof` が許可されています。これは、渡された式の型の共用体型を返します

typeof(1 + 2)  # => Int32
typeof(1, "a") # => (Int32 | String)