Define a new type, mytype
:
type :: mytype
integer :: int
real :: float
end type mytype
Declare a variable of type mytype:
type(mytype) :: foo
The components of a derived type can be accessed with the %
operator1:
foo%int = 4
foo%float = 3.142
A Fortran 2003 feature (not yet implemented by all compilers) allows to define parameterized data types:
type, public :: matrix(rows, cols, k)
integer, len :: rows, cols
integer, kind :: k = kind(0.0)
real(kind = k), dimension(rows, cols) :: values
end type matrix
The derived type matrix
has three type parameters which are listed in parentheses following the type name (they are rows
, cols
, and k
). In the declaration of each type parameter it must be indicated whether they are kind (kind
) or length (len
) type parameters.
Kind type parameters, like those of the intrinsic types, must be constant expressions whereas length type parameters, like the length of an intrinsic character variable, may vary during execution.
Note that parameter k
has a default value, so it may be provided or omitted when a variable of type matrix
is declared, as follows
type (matrix (55, 65, kind=double)) :: b, c ! default parameter provided
type (matrix (rows=40, cols=50) :: m ! default parameter omitted
The name of a derived type may not be doubleprecision
or the same as any of the intrinsic types.
%
as the component-access operator, instead of the more common .
. This is because .
is already taken by the operator syntax, i.e. .not.
, .and.
, .my_own_operator.
.