In this Lisp translation, we use unwind-protect to mimic the behavior of Go’s defer. The unwind-protect macro ensures that its cleanup forms (in this case, closing the file) are executed when control leaves the protected form, whether normally or due to a non-local exit (like an error).
The create-file function opens a file for writing, write-file writes to it, and close-file closes it, handling any potential errors.
Note that Lisp doesn’t have a direct equivalent to Go’s defer, but unwind-protect provides similar functionality for resource management and cleanup. The handler-case macro is used for error handling in the close-file function, similar to how the Go version checks for errors when closing the file.
To run this Lisp program, you would typically save it to a file (e.g., defer.lisp) and then run it using a Lisp implementation like SBCL (Steel Bank Common Lisp):
This demonstrates that the file operations occur in the expected order, with the file being closed after it’s written to, just like in the original Go example.