D 程式設計 - 元組



元組用於將多個值組合成單個物件。元組包含一系列元素。這些元素可以是型別、表示式或別名。元組的個數和元素在編譯時固定,並且在執行時無法更改。

元組兼具結構體和陣列的特性。元組元素可以像結構體一樣具有不同的型別。元素可以透過索引訪問,就像陣列一樣。它們透過 std.typecons 模組中的 Tuple 模板作為庫特性實現。Tuple 利用 std.typetuple 模組中的 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 模板建立元組

元組也可以直接透過 Tuple 模板構造,而不是使用 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,"\t",b,"\t",c,"\t",d); 
}
 
void method2(int a, float b, char c) { 
   writeln("method 2 ",a,"\t",b,"\t",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,"\t",b,"\t",c,"\t",d); 
} 

void method2(TL tl) { 
   writeln(tl[0],"\t", 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
廣告

© . All rights reserved.