Structs in Co-array Fortran

Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.

program structs
    implicit none
    
    type :: person
        character(len=100) :: name
        integer :: age
    end type person

    ! Function to create a new person
    type(person) function newPerson(name) result(p)
        character(len=*), intent(in) :: name
        p%name = name
        p%age = 42
    end function newPerson
    
    ! Variables declaration
    type(person) :: p
    type(person), pointer :: pp
    
    ! Create and print new person records
    call printPerson(person('Bob', 20))
    call printPerson(person('Alice', 30))
    call printPerson(person('Fred', 0))
    
    ! Create and print a pointer to a new person
    pp => person('Ann', 40)
    call printPersonPtr(pp)

    ! Use constructor function to create and print new person
    pp => newPerson('Jon')
    call printPersonPtr(pp)
    
    ! Access struct fields and demonstrate mutability
    p = person('Sean', 50)
    print *, p%name
    pp => p
    print *, pp%age

    ! Modify the age field
    pp%age = 51
    print *, pp%age

    ! Anonymous struct example, useful for table-driven tests
    call printDog('Rex', .true.)

contains

    ! Subroutine to print person details
    subroutine printPerson(p)
        type(person), intent(in) :: p
        print *, p
    end subroutine printPerson

    ! Subroutine to print details of a person pointer
    subroutine printPersonPtr(pp)
        type(person), pointer :: pp
        print *, pp
    end subroutine printPersonPtr

    ! Subroutine to print dog details
    subroutine printDog(name, isGood)
        character(len=*), intent(in) :: name
        logical, intent(in) :: isGood
        type, bind(c) :: dog
            character(len=100) :: name
            logical :: isGood
        end type dog
        type(dog) :: d
        d%name = name
        d%isGood = isGood
        print *, d
    end subroutine printDog

end program structs

To run the program, compile it with your Fortran compiler and then execute it.

$ gfortran structs.f90 -o structs
$ ./structs
 Bob          20
 Alice        30
 Fred         0
 Ann          40
 Jon          42
 Sean
 50
 51
 Rex           T

Structs in Fortran are similar to those in other languages, allowing you to group related data together. The concept of pointers and constructors can also be leveraged to work with these structures more efficiently.

Next example: Methods.