Derived types
| Define a type | |
| Use it | |
| Structure constructors | |
| Nest types |
Define a type
A derived type bundles related data into one named unit, so a point can hold x and y together instead of two loose variables.
Declare it with the type statement, list each component on its own line, and close the block with end type.
The example below defines a simple point with two real components.
program demo
implicit none
type :: point
real :: x
real :: y
end type point
end program demo
Use it
Declare a variable of the new type and reach each component with the percent sign, as in p%x for the x part of p.
Components behave like ordinary variables: assign them, read them, and pass them to procedures one by one.
The program below stores two coordinates and prints them.
program demo
implicit none
type :: point
real :: x
real :: y
end type point
type(point) :: p
p%x = 1.0
p%y = 2.0
print *, p%x, p%y
end program demo
Structure constructors
A structure constructor builds a whole value in one expression by naming the type and listing the components in order.
It keeps initialization short and makes the starting state of the variable visible on a single line.
The next program creates a point with one constructor call and prints the full value.
program demo
implicit none
type :: point
real :: x
real :: y
end type point
type(point) :: p
p = point(1.0, 2.0)
print *, p
end program demo
Nest types
A component of one derived type can itself be a derived type, which builds larger models from small tested pieces.
Define the inner type first, then use it as the declared type of a component in the outer type.
Here a circle holds a point as its center plus a radius, and the program reaches the nested x with two percent signs.
program demo
implicit none
type :: point
real :: x
real :: y
end type point
type :: circle
type(point) :: center
real :: radius
end type circle
type(circle) :: c
c%center = point(0.0, 0.0)
c%radius = 5.0
print *, c%center%x, c%radius
end program demo
Next: Type-bound procedures
Article author: Arthur Isaev