Struct Embedding in Pascal

Pascal supports record types, which are similar to structs in other languages. We can use these to express a more seamless composition of types.

program StructEmbedding;

uses
  SysUtils;

type
  TBase = record
    num: Integer;
    function Describe: string;
  end;

  TContainer = record
    base: TBase;
    str: string;
  end;

function TBase.Describe: string;
begin
  Result := Format('base with num=%d', [num]);
end;

var
  co: TContainer;
  d: TBase;

begin
  // When creating records, we initialize the fields explicitly
  co.base.num := 1;
  co.str := 'some name';

  // We can access the base's fields through the container
  WriteLn(Format('co={num: %d, str: %s}', [co.base.num, co.str]));

  // We can also access the base fields directly
  WriteLn('also num: ', co.base.num);

  // We can call methods from the base record
  WriteLn('describe: ', co.base.Describe);

  // In Pascal, we don't have interfaces like in some other languages,
  // but we can still use the base record's methods through the container
  d := co.base;
  WriteLn('describer: ', d.Describe);
end.

To run this program, save it as struct_embedding.pas and compile it using a Pascal compiler like Free Pascal:

$ fpc struct_embedding.pas
$ ./struct_embedding
co={num: 1, str: some name}
also num: 1
describe: base with num=1
describer: base with num=1

In this Pascal version, we’ve used records to mimic the struct embedding concept. The TContainer record includes a TBase record as a field, allowing us to access the base’s fields and methods through the container.

Pascal doesn’t have a direct equivalent to Go’s struct embedding, so we’ve had to explicitly access the base record’s fields and methods through the base field of the container. This achieves a similar effect to Go’s embedding, albeit with slightly different syntax.

The concept of interfaces as seen in Go is not present in standard Pascal. However, we can still demonstrate the use of the base record’s methods through the container, which captures the essence of the original example.