Multiple Return Values in Co-array Fortran

Co-array Fortran supports multiple return values through the use of derived types. Here’s an example demonstrating this feature:

module multiple_return_values
  implicit none

  type :: dual_int
    integer :: first, second
  end type dual_int

contains
  function vals() result(result)
    type(dual_int) :: result
    result = dual_int(3, 7)
  end function vals

  subroutine main()
    type(dual_int) :: result
    integer :: a, b, c

    ! Here we use the 2 different return values from the call
    result = vals()
    a = result%first
    b = result%second
    print *, a
    print *, b

    ! If you only want a subset of the returned values,
    ! you can ignore one of the components
    result = vals()
    c = result%second
    print *, c
  end subroutine main
end module multiple_return_values

program run_example
  use multiple_return_values
  call main()
end program run_example

In this Co-array Fortran code:

  1. We define a derived type dual_int to simulate multiple return values.

  2. The vals() function returns a dual_int object containing two integers.

  3. In the main subroutine, we demonstrate how to use these multiple return values:

    • First, we assign both values to separate variables.
    • Then, we show how to use only one of the returned values.
  4. The print * statements are used to output the results.

To run this program, you would typically save it in a file (e.g., multiple_return_values.f90), compile it, and then execute the resulting binary:

$ gfortran -coarray=single multiple_return_values.f90 -o multiple_return_values
$ ./multiple_return_values
           3
           7
           7

Note that Co-array Fortran doesn’t have a direct equivalent to Go’s blank identifier _. Instead, we simply don’t use the component we’re not interested in.

While Co-array Fortran doesn’t have built-in support for multiple return values like Go, using derived types allows us to achieve similar functionality in a type-safe manner.