Defer in OCaml

In OCaml, there isn’t a direct equivalent to Go’s defer keyword. However, we can achieve similar functionality using the finally clause in exception handling. Here’s how we could implement a similar concept:

open Printf

(* Simulating file operations *)
type file = {
  name: string;
  mutable is_open: bool;
}

let create_file path =
  printf "creating\n";
  { name = path; is_open = true }

let write_file f =
  printf "writing\n";
  if f.is_open then
    printf "data\n"
  else
    failwith "Cannot write to closed file"

let close_file f =
  printf "closing\n";
  if f.is_open then
    f.is_open <- false
  else
    failwith "File already closed"

(* Main function *)
let main () =
  let f = create_file "/tmp/defer.txt" in
  try
    write_file f;
    (* Other operations can go here *)
  with e ->
    close_file f;
    raise e
  ;
  close_file f

let () = main ()

In this OCaml version, we’ve simulated file operations using a custom file type. The main function demonstrates how to use exception handling to ensure that the file is closed, similar to how defer works in the original example.

Here’s a breakdown of the code:

  1. We define a file type to represent our file operations.

  2. create_file, write_file, and close_file functions simulate file operations.

  3. In the main function, we use a try...with block. The close_file f operation is placed in both the with clause and after the try block. This ensures that the file is closed whether an exception occurs or not, similar to the behavior of defer in the original example.

  4. If an exception occurs, the file is closed in the with clause, and then the exception is re-raised.

  5. If no exception occurs, the file is closed after all operations are completed.

To run this program:

$ ocamlc defer.ml -o defer
$ ./defer
creating
writing
closing

This approach ensures that resources are properly managed and cleaned up, similar to the defer mechanism in Go, although the syntax and implementation details differ due to the nature of OCaml’s exception handling system.