# Dart Typedef

`typedef`或函式型別別名有助於定義指向記憶體中可執行程式碼的指標。簡單地說，`typedef`可以用作參照函式的指標。

`typedef`可用於指定希望特定函式匹配的函式簽名。函式簽名由函式的引數(包括其型別)定義。返回型別不是函式簽名的一部分。語法如下 -

``````typedef function_name(parameters)
``````

`typedef`的變數可以指向與`typedef`具有相同簽名的函式。可以使用以下簽名將函式分配給`typedef`變數。

``````type_def  var_name = function_name
``````

`typedef`變數可用於呼叫函式。以下是呼叫函式的方法 -

``````var_name(parameters)
``````

#### 範例

``````typedef ManyOperation(int firstNo , int secondNo); //function signature
``````

``````Add(int firstNo,int second){
print("Add result is \${firstNo+second}");
}
Subtract(int firstNo,int second){
print("Subtract result is \${firstNo-second}");
}
Divide(int firstNo,int second){
print("Add result is \${firstNo/second}");
}
``````

``````ManyOperation oper ;

//can point to any method of same signature
oper = Add;
oper(10,20);
oper = Subtract;
oper(30,20);
oper = Divide;
oper(50,5);
``````

`oper`變數可以指向任何採用兩個整數引數的方法。`Add`函式的參照賦給變數。`typedef`可以在執行時切換函式參照。

``````typedef ManyOperation(int firstNo , int secondNo);
//function signature

Add(int firstNo,int second){
print("Add result is \${firstNo+second}");
}
Subtract(int firstNo,int second){
print("Subtract result is \${firstNo-second}");
}
Divide(int firstNo,int second){
print("Divide result is \${firstNo/second}");
}
Calculator(int a, int b, ManyOperation oper){
print("Inside calculator");
oper(a,b);
}
void main(){
ManyOperation oper = Add;
oper(10,20);
oper = Subtract;
oper(30,20);
oper = Divide;
oper(50,5);
}
``````

``````Add result is 30
Subtract result is 10
Divide result is 10.0
``````

#### 範例

`typedef`也可以作為引數傳遞給函式。閱讀以下範例程式碼 -

``````typedef ManyOperation(int firstNo , int secondNo);   //function signature
Add(int firstNo,int second){
print("Add result is \${firstNo+second}");
}
Subtract(int firstNo,int second){
print("Subtract result is \${firstNo-second}");
}
Divide(int firstNo,int second){
print("Divide result is \${firstNo/second}");
}
Calculator(int a,int b ,ManyOperation oper){
print("Inside calculator");
oper(a,b);
}
main(){
Calculator(5,5,Add);
Calculator(5,5,Subtract);
Calculator(5,5,Divide);
}
``````

``````Inside calculator
Add result is 10
Inside calculator
Subtract result is 0
Inside calculator
Divide result is 1.0
``````