从其它平台迁移而来


结构体的方法

Delphi

Delphi结构体的方法与类的方法几乎是一致的,主要区别是内存的管理方式和可见性不同。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
//定义
type
  TMyStruct = record
    No: Integer;
    Name: string;
    function ToString: string;
  end;
//实现
function TMyStruct.ToString: string;
begin
  Result := Format('No:%d, Name:%s', [Self.No, Self.Name]);
end;
//调用
var ms: TMyStruct; s: string;
begin
  s := ms.ToString;
end;

Go

方法其实就是加了接收器的函数,语法如下:

1
2
3
func (接收器变量 接收器类型) 方法名(参数列表) (返回参数) {
  函数体
}

Go结构体的方法无需声明,直接实现即可。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
//结构体定义
type MyStruct struct {
  No   int
  Name string
}
//结构体方法实现
func (s MyStruct) ToString() string {
  return fmt.Sprintf("No:%d, Name:%s", s.No, s.Name)
}
//调用
var ms MyStruct
s := ms.ToString()

类型的方法

Delphi

Delphi 2009以后,类型也可以有方法,最常用的是各基本类型的ToString方法。Integer类型的方法源码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//Integer 类型的方法声明
TIntegerHelper = record helper for Integer { for LongInt type too }
  public
    const
      MaxValue = 2147483647;
      MinValue = -2147483648;
    function ToString: string; overload; inline;
    function ToBoolean: Boolean; inline;
    function ToHexString: string; overload; inline;
    function ToHexString(const MinDigits: Word): string; overload; inline;
    function ToSingle: Single; inline;
    function ToDouble: Double; inline;
    function ToExtended: Extended; inline;
    class function Size: Integer; inline; static;
    class function ToString(const Value: Integer): string; overload; inline; static;
    class function Parse(const S: string): Integer; inline; static;
    class function TryParse(const S: string; out Value: Integer): Boolean; inline; static;
  end;

//Integer 类型的 ToString 方法实现
function TIntegerHelper.ToString: string;
begin
  Result := IntToStr(Self);
end;

可以看出,Delphi类型的方法是在结构体方法的基础上实现的。

Go

Go也可以为类型添加方法,但类型的定义类型的方法必须在同一个包中

1
2
3
4
type myInt int
func (i myInt) ToString() string {
  return strconv.Itoa(i)
}

可以看出,在Go中,结构体只是众多类型中的一种,结构体的方法也只是类型的方法的其中一种。Go没有严格的的概念,但是通过类型和方法的组合完全可以实现类的功能。