Defer in Pascal

Here’s the Pascal translation of the Go “Defer” example, formatted in Markdown suitable for Hugo:

Pascal doesn’t have a direct equivalent to Go’s defer keyword. However, we can achieve similar functionality using a try-finally block. Here’s how we can implement the same behavior:

program DeferExample;

uses
  SysUtils;

var
  f: TextFile;

procedure CreateFile(path: string);
begin
  WriteLn('creating');
  AssignFile(f, path);
  try
    Rewrite(f);
  except
    on E: Exception do
    begin
      WriteLn('Error creating file: ', E.Message);
      Halt(1);
    end;
  end;
end;

procedure WriteToFile;
begin
  WriteLn('writing');
  WriteLn(f, 'data');
end;

procedure CloseFile;
begin
  WriteLn('closing');
  try
    Close(f);
  except
    on E: Exception do
    begin
      WriteLn(ErrOutput, 'Error: ', E.Message);
      Halt(1);
    end;
  end;
end;

begin
  CreateFile('/tmp/defer.txt');
  try
    WriteToFile;
  finally
    CloseFile;
  end;
end.

In this Pascal example, we’ve recreated the functionality of the original code using a try-finally block. Here’s how it works:

  1. We define procedures for creating, writing to, and closing the file, similar to the original functions.

  2. In the CreateFile procedure, we use AssignFile and Rewrite to create a new file. We wrap this in a try-except block to handle any errors.

  3. The WriteToFile procedure writes data to the file, just like in the original example.

  4. The CloseFile procedure closes the file and handles any potential errors.

  5. In the main program, we use a try-finally block to ensure that the file is closed even if an exception occurs during writing. This mimics the behavior of defer in the original code.

To run this program:

$ fpc defer_example.pas
$ ./defer_example
creating
writing
closing

This Pascal version achieves the same result as the original code, ensuring that the file is properly closed after writing, even in the case of an error. While Pascal doesn’t have a built-in defer mechanism, the try-finally construct provides a similar way to ensure cleanup code is executed.