从其它平台迁移而来


早期的Delphi版本是没有匿名函数的,不过可以定义一个函数类型来实现类似的功能;后期的版本已经支持匿名函数,随用随写。Go天生就支持匿名函数。

Delphi

函数类型

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//声明函数类型
type
  TMyProc = procedure(A: Integer);         //过程
  TMyFunc = function(x: Integer): Integer; //函数
//定义符合函数类型的函数
procedure MyProc(A: Integer);
begin
  ShowMessage(IntToHex(A));
end;
function MyFunc1(x: Integer): Integer;
begin
  Result := x + x;
end;
function MyFunc2(x: Integer): Integer;
begin
  Result := x * x;
end;
//使用
var
  mp: TMyProc;
  mf: TMyFunc;
begin
  mp := MyProc;
  mf := MyFunc1;
  mp(mf(99));
end;
//作为参数进行传递,这才是函数类型最主要的使用方法
procedure Test(x: Integer; Func: TMyFunc);
begin
  ShowMessage(Func(x).ToString);
end;
Test(123, MyFunc1);
Test(123, MyFunc2);

回调函数是函数类型最典型的应用,类的事件可以看作是特殊的回调函数。

匿名函数

匿名函数的好处是可以随用随写,而不必事先把可能用到的实现都写好,而且尽可能把代码块的作用域缩到最小。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
//定义匿名函数类型
type TF = reference to function(n: Integer): string;
//使用
var f: TF;
begin
  f :=
    function(a: Integer): string //注意,此处无分号
    begin
      Result := a.ToString;
    end;
  ShowMessage(f(123));
  f := nil;                      //匿名函数内代码的作用域到再次给匿名函数变量赋值为止
end;

匿名函数的用法与函数类型的用法一致。另外,Delphi已经提供好了几个常用的匿名函数类型:TProcTProc<T>TProc<T1,T2>TProc<T1,T2,T3>TProc<T1,T2,T3,T4>TFunc<TResult>TFunc<T,TResult>TFunc<T1,T2,TResult>TFunc<T1,T2,T3,TResult>TFunc<T1,T2,T3,T4,TResult>TPredicate<T>

Delphi还有一种常见的缩小函数作用域的写法,作用域是整个调用函数内,比匿名函数的作用域略大:

1
2
3
4
5
6
7
8
procedure Test(x: Integer);
  function Func(A: Integer): Integer; //整个Test函数内均可调用
  begin
    Result := A * A;
  end;
begin
  ShowMessage(Func(x).ToString);
end;

Go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
//匿名函数定义
func(形参列表)(返回值列表){
  函数体
}
//定义的同时并进行调用
func(形参列表)(返回值列表){
  函数体
}(实参列表)
//赋值给变量
f := func(形参列表)(返回值列表){
  函数体
}  //之后可以使用f(实参列表)进行调用