Defer in Co-array Fortran

In Co-array Fortran, there isn’t a direct equivalent to the defer keyword. However, we can achieve similar functionality using subroutines and explicit calls. Here’s how we might structure a similar program:

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)
    
contains

    subroutine create_file(filename, unit)
        character(len=*), intent(in) :: filename
        integer, intent(out) :: unit
        integer :: iostat
        
        print *, "creating"
        open(newunit=unit, file=filename, status='replace', action='write', iostat=iostat)
        if (iostat /= 0) then
            error stop "Error creating file"
        end if
    end subroutine create_file
    
    subroutine write_file(unit)
        integer, intent(in) :: unit
        
        print *, "writing"
        write(unit, *) "data"
    end subroutine write_file
    
    subroutine close_file(unit)
        integer, intent(in) :: unit
        integer :: iostat
        
        print *, "closing"
        close(unit, iostat=iostat)
        if (iostat /= 0) then
            write(error_unit, *) "Error closing file"
            error stop
        end if
    end subroutine close_file
    
end program main

In this Co-array Fortran version:

  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 assigns it a 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. Error handling is done using error stop and writing to error_unit for critical errors.

While Co-array Fortran doesn’t have a built-in defer mechanism, we achieve a similar effect by explicitly calling the close_file subroutine at the end of our main program. This ensures that the file is closed after we’re done writing to it.

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

$ gfortran -coarray=single defer.f90 -o defer
$ ./defer
creating
writing
closing

This example demonstrates how to structure a program in Co-array Fortran to manage resources (in this case, a file) in a way that ensures proper cleanup, similar to the use of defer in other languages.