A type definition groups named fields. The auto-generated structure constructor builds an instance.

Program

Play the program to build a rectangle and compute its area from fields.

derived_type.f90
Replay: real traced execution (multi-file project)
program derived_type_demo
    implicit none
    type :: rectangle
        integer :: width
        integer :: height
    end type rectangle
    type(rectangle) :: rect
    integer :: area_val
    rect = rectangle(4, 3)
    area_val = rect%width * rect%height
    print '(I0)', area_val
end program derived_type_demo
  1. rect ← rectangle(width=4, height=3)

    8integer :: area_val9rect = rectangle(4, 3)10area_val = rect%width * rect%height
    values this steprectangle(width=4, height=3)rect
  2. area_val ← 12

    9rect = rectangle(4, 3)10area_val = rect%width * rect%height11print '(I0)', area_val
    values this step12area_val4rect%width3rect%height
  3. print '(I0)', area_val

    10    area_val = rect%width * rect%height11    print '(I0)', area_val12end program derived_type_demo
    output12
    values this step12area_val

Follow the Rectangle

  1. type rectangle groups width and height.
  2. rect = rectangle(4, 3) stores width 4 and height 3.
  3. rect%width reads 4.
  4. rect%height reads 3.
  5. area_val = 4 * 3 becomes 12, and the program prints 12. | field | value | | --- | --- | | rect%width | 4 | | rect%height | 3 | | area_val | 12 |
type `type :: rectangle ... end type` defines a record.
constructor `rectangle(4, 3)` builds an instance positionally.
% access `rect%width` reads one field.

Exercise: derived_type.f90

Reproduce the printed value 12, then change width or height and predict the new area before running it.