D語言元組

元組用於組合多個值作爲單個對象。元組包含的元素的序列。元素可以是類型,表達式或別名。元組的數目和元件固定在編譯時,它們不能在運行時改變。

元組有兩個結構和數組的特性。元組元素可以是不同的類型,如結構的。該元素可以通過索引數組一樣訪問。它們是由從std.typecons模塊的元組模板實現爲一個庫功能。元組利用TypeTuple從一些業務的std.typetuple模塊。

使用元組tuple()

元組可以由函數tuple()來構造。一個元組的成員由索引值訪問。一個例子如下所示。

import std.stdio; import std.typecons; void main() { auto myTuple = tuple(1, "Tuts"); writeln(myTuple); writeln(myTuple[0]); writeln(myTuple[1]); }

當上面的代碼被編譯並執行,它會產生以下結果:

Tuple!(int, string)(1, "Tuts")
1
Tuts

使用元組元組模板

元組也可以由元組模板而不是tuple()函數直接構造。每個成員的類型和名稱被指定爲兩個連續的模板參數。它可以通過屬性使用模板創建的時候訪問的成員。

import std.stdio; import std.typecons; void main() { auto myTuple = Tuple!(int, "id",string, "value")(1, "Tuts"); writeln(myTuple); writeln("by index 0 : ", myTuple[0]); writeln("by .id : ", myTuple.id); writeln("by index 1 : ", myTuple[1]); writeln("by .value ", myTuple.value); }

當上面的代碼被編譯並執行,它會產生以下結果:

Tuple!(int, "id", string, "value")(1, "Tuts")
by index 0 : 1
by .id : 1
by index 1 : Tuts
by .value Tuts

擴展屬性和函數參數

元組的成員可以通過.expand擴展屬性或通過切片進行擴展。這種擴展/切片值可以作爲函數的參數列表。一個例子如下所示。

import std.stdio; import std.typecons; void method1(int a, string b, float c, char d) { writeln("method 1 ",a," ",b," ",c," ",d); } void method2(int a, float b, char c) { writeln("method 2 ",a," ",b," ",c); } void main() { auto myTuple = tuple(5, "my string", 3.3, 'r'); writeln("method1 call 1"); method1(myTuple[]); writeln("method1 call 2"); method1(myTuple.expand); writeln("method2 call 1"); method2(myTuple[0], myTuple[$-2..$]); }

當上面的代碼被編譯並執行,它會產生以下結果:

method1 call 1
method 1 5 my string 3.3 r
method1 call 2
method 1 5 my string 3.3 r
method2 call 1
method 2 5 3.3 r

TypeTuple

TypeTuple在std.typetuple模塊中定義。值和類型的逗號分隔的列表。使用TypeTuple一個簡單的例子如下。 TypeTuple用於創建參數列表,模板列表和數組文本列表。

import std.stdio; import std.typecons; import std.typetuple; alias TypeTuple!(int, long) TL; void method1(int a, string b, float c, char d) { writeln("method 1 ",a," ",b," ",c," ",d); } void method2(TL tl) { writeln(tl[0]," ", tl[1] ); } void main() { auto arguments = TypeTuple!(5, "my string", 3.3,'r'); method1(arguments); method2(5, 6L); }

當上面的代碼被編譯並執行,它會產生以下結果:

method 1 5 my string 3.3 r
5 6