元組¶
一個 元組 通常使用元組字面值建立
tuple = {1, "hello", 'x'} # Tuple(Int32, String, Char)
tuple[0] # => 1 (Int32)
tuple[1] # => "hello" (String)
tuple[2] # => 'x' (Char)
要建立一個空的元組請使用 Tuple.new。
要表示元組類型,您可以寫成
# The type denoting a tuple of Int32, String and Char
Tuple(Int32, String, Char)
在類型限制、泛型類型引數以及其他需要類型的地方,您可以使用較短的語法,如 類型文法 中所述
# An array of tuples of Int32, String and Char
Array({Int32, String, Char})
Splat 展開¶
Splat 運算子可以在元組字面值內使用,一次展開多個值。被展開的值必須是另一個元組。
tuple = {1, *{"hello", 'x'}, 2} # => {1, "hello", 'x', 2}
typeof(tuple) # => Tuple(Int32, String, Char, Int32)
tuple = {3.5, true}
tuple = {*tuple, *tuple} # => {3.5, true, 3.5, true}
typeof(tuple) # => Tuple(Float64, Bool, Float64, Bool)