Methods in Pascal

Our first example demonstrates how to define methods on struct types in Pascal.

program Methods;

uses
  SysUtils;

type
  TRect = record
    width, height: Integer;
  end;

// This area method is associated with the TRect type
function Area(const r: TRect): Integer;
begin
  Result := r.width * r.height;
end;

// This perim method is also associated with the TRect type
function Perim(const r: TRect): Integer;
begin
  Result := 2 * r.width + 2 * r.height;
end;

var
  r: TRect;
begin
  r.width := 10;
  r.height := 5;

  // Here we call the 2 methods defined for our record
  WriteLn('area: ', Area(r));
  WriteLn('perim:', Perim(r));

  // Pascal doesn't have pointers in the same way as Go,
  // so we don't need to demonstrate pointer receivers here
end.

In this Pascal example, we define a TRect record type, which is similar to a struct in other languages. We then define two functions, Area and Perim, which operate on TRect values.

Pascal doesn’t have the concept of methods attached directly to types like Go does. Instead, we define regular functions that take the record as a parameter. This achieves a similar result to Go’s methods.

In the begin block (which is similar to the main function in Go), we create a TRect instance, set its width and height, and then call our functions, passing the record as an argument.

To run this program, you would typically save it as methods.pas, compile it with a Pascal compiler, and then run the resulting executable.

$ fpc methods.pas
$ ./methods
area: 50
perim: 30

Pascal doesn’t have the same concept of pointer and value receivers as Go does. In Pascal, you can pass records by value or by reference (using the var keyword in the function parameter), but the syntax for calling the function remains the same either way.

Next, we’ll look at Pascal’s mechanism for defining interfaces, which allow for polymorphic behavior across different types.