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:
We define procedures for creating, writing to, and closing the file, similar to the original functions.
In the
CreateFileprocedure, we useAssignFileandRewriteto create a new file. We wrap this in atry-exceptblock to handle any errors.The
WriteToFileprocedure writes data to the file, just like in the original example.The
CloseFileprocedure closes the file and handles any potential errors.In the main program, we use a
try-finallyblock to ensure that the file is closed even if an exception occurs during writing. This mimics the behavior ofdeferin the original code.
To run this program:
$ fpc defer_example.pas
$ ./defer_example
creating
writing
closingThis 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.