Defer in Fortran

Fortran does not have a direct equivalent to the defer keyword in Go. However, we can achieve similar functionality using subroutines and explicit calls. Here’s how we can implement a similar concept in Fortran:

program main
    use iso_fortran_env, only: error_unit
    implicit none
    
    integer :: file_unit
    
    call create_file("/tmp/defer.txt", file_unit)
    call write_file(file_unit)
    call close_file(file_unit)
end program main

subroutine create_file(filename, file_unit)
    character(len=*), intent(in) :: filename
    integer, intent(out) :: file_unit
    integer :: iostat
    
    print *, "creating"
    open(newunit=file_unit, file=filename, status='replace', iostat=iostat)
    if (iostat /= 0) then
        print *, "Error opening file"
        stop
    end if
end subroutine create_file

subroutine write_file(file_unit)
    integer, intent(in) :: file_unit
    
    print *, "writing"
    write(file_unit, *) "data"
end subroutine write_file

subroutine close_file(file_unit)
    use iso_fortran_env, only: error_unit
    integer, intent(in) :: file_unit
    integer :: iostat
    
    print *, "closing"
    close(file_unit, iostat=iostat)
    if (iostat /= 0) then
        write(error_unit, *) "Error closing file"
        stop 1
    end if
end subroutine close_file

In this Fortran version, we’ve created a program that performs similar operations to the original example. Here’s a breakdown of the changes and explanations:

  1. We define a main program that calls subroutines to create, write to, and close a file.

  2. The create_file subroutine opens a file and returns the file unit number.

  3. The write_file subroutine writes data to the file.

  4. The close_file subroutine closes the file and checks for any errors during closing.

  5. We use explicit error handling with iostat to check for errors when opening and closing the file.

  6. Instead of using defer, we explicitly call the close_file subroutine at the end of the main program.

To run the program, you would typically compile it and then execute the resulting binary:

$ gfortran -o defer_example defer_example.f90
$ ./defer_example
creating
writing
closing

This Fortran implementation achieves a similar result to the original example, demonstrating file operations with proper error handling. While it doesn’t have the automatic deferred execution that Go’s defer provides, it follows a similar pattern of ensuring that the file is closed after it’s been written to.