Methods in Co-array Fortran

module rect_module
  implicit none
  private
  public :: rect, area, perim

  type rect
    integer :: width, height
  end type rect

contains
  ! This 'area' function calculates the area of a rectangle
  function area(r) result(a)
    type(rect), intent(in) :: r
    integer :: a
    a = r%width * r%height
  end function area

  ! This 'perim' function calculates the perimeter of a rectangle
  function perim(r) result(p)
    type(rect), intent(in) :: r
    integer :: p
    p = 2*r%width + 2*r%height
  end function perim
end module rect_module

program main
  use rect_module
  implicit none

  type(rect) :: r
  r = rect(width=10, height=5)

  ! Here we call the 2 functions defined for our type
  print *, "area: ", area(r)
  print *, "perim:", perim(r)

  ! Co-array Fortran doesn't have pointers like Go,
  ! so we'll just use the same variable
  print *, "area: ", area(r)
  print *, "perim:", perim(r)

end program main

This Co-array Fortran code demonstrates the concept of user-defined types and associated procedures, which is similar to methods in object-oriented programming languages.

In Co-array Fortran, we define a module rect_module that encapsulates the rect type and its associated procedures area and perim. These procedures are similar to methods in Go, but they’re implemented as module procedures rather than being attached directly to the type.

The rect type is defined with width and height components, similar to the struct in the original code.

The area and perim functions take a rect as an argument and perform calculations on it. This is analogous to methods in Go, but the syntax is different.

In the main program, we create a rect instance, call the functions, and print the results.

Co-array Fortran doesn’t have pointers in the same way as Go, so we don’t demonstrate pointer vs. value semantics. Instead, we simply call the functions twice to mirror the structure of the original example.

To compile and run this program, you would typically use a Co-array Fortran compiler. The exact commands may vary depending on your specific compiler, but it might look something like this:

$ caf rect_program.f90
$ ./a.out
area:  50
perim: 30
area:  50
perim: 30

Note that Co-array Fortran is an extension of Fortran for parallel programming, but this example doesn’t use any of its parallel features. The core concepts of types and procedures shown here are common to standard Fortran as well.