From Delphi to Go -- Method

Method of structure

Delphi

The method of Delphi structure is almost the same as that of class. The main difference is the memory management and visibility.

//Definition
type
  TMyStruct = record
    No: Integer;
    Name: string;
    function ToString: string;
  end;
//Realization
function TMyStruct.ToString: string;
begin
  Result := Format('No:%d, Name:%s', [Self.No, Self.Name]);
end;
//call
var ms: TMyStruct; s: string;
begin
  s := ms.ToString;
end;

Go

The method is to add the function of the receiver. The syntax is as follows:

func (receiver variable receiver type) method name (parameter list) (return parameter){
  Function body
}

The methods of the Go structure do not need to be declared, but can be implemented directly.

//Definition of structure
type MyStruct struct {
  No   int
  Name string
}
//Implementation of structure method
func (s MyStruct) ToString() string {
  return fmt.Sprintf("No:%d, Name:%s", s.No, s.Name)
}
//call
var ms MyStruct
s := ms.ToString()

Method of type

Delphi

After Delphi 2009, types can also have methods, the most commonly used is the ToString method of each basic type. The source code of Integer type method is as follows:

//Method declaration of Integer type
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;

//Implementation of ToString method of Integer type
function TIntegerHelper.ToString: string;
begin
  Result := IntToStr(Self);
end;

It can be seen that the Delphi type method is implemented on the basis of the structure method.

Go

Go can also add a method for a type, but the definition of the type and the method of the type must be in the same package.

type myInt int
func (i myInt) ToString() string {
  return strconv.Itoa(i)
}

It can be seen that in go, a structure is only one of many types, and its method is only one of them. Go has no strict concept of class, but it can fully realize the function of class through the combination of type and method.

Tags: Programming Delphi

Posted on Tue, 03 Dec 2019 16:02:58 -0800 by NoDoze