跳至內容

類型語法

為了一些常見的類型提供了方便的語法。這些在編寫C 綁定時特別有用,但可以在上述任何位置使用。

路徑與泛型

可以使用常規類型和泛型

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

聯集

alias Int32OrString = Int32 | String

類型中的管道符號 (|) 會建立聯集類型。Int32 | String 讀作「Int32 或 String」。在常規程式碼中,Int32 | String 表示在 Int32 上調用方法 |,並將 String 作為參數。

可空值

alias Int32OrNil = Int32?

與以下相同

alias Int32OrNil = Int32 | ::Nil

在常規程式碼中,Int32? 本身就是一個 Int32 | ::Nil 聯集類型。

指標

alias Int32Ptr = Int32*

與以下相同

alias Int32Ptr = Pointer(Int32)

在常規程式碼中,Int32* 表示在 Int32 上調用 * 方法。

靜態陣列

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} 是一個元組實例,其中包含 Int32String 作為其元素。這與上面的元組**類型**不同。

具名元組

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

與以下相同

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

在常規程式碼中,{x: Int32, y: String} 是一個具名元組實例,其中包含 xInt32yString。這與上面的具名元組**類型**不同。

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)