typestar

Derived types in Fortran

A kayak record built with type and read with the percent sign.

program derived_types
    implicit none
    ! A derived type bundles fields; % reaches into them.
    type :: kayak
        character(len=10) :: model
        integer :: length_ft
        logical :: rudder
    end type kayak

    type(kayak) :: stock, custom

    stock = kayak("Petrel", 17, .false.)
    custom = kayak(model="Auk", length_ft=14, rudder=.true.)

    print *, "stock:  ", stock%model, stock%length_ft, " ft"
    print *, "custom: ", custom%model, " rudder? ", custom%rudder
end program derived_types

How it works

  1. type :: kayak ... end type bundles a name, a length, and a rudder flag.
  2. kayak("Petrel", 17, .false.) constructs positionally; keywords work too.
  3. stock%model reaches into a field — % is Fortran's dot.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
455
Tokens
94
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 1 of 3 in Types & memory, step 19 of 27 in Language basics.

← Previous Next →