Derived Types

Intrinsic assignment copies all components (deep-copying allocatable components, shallow-copying pointers).

16.1 Defining and using types

module particles
  use, intrinsic :: iso_fortran_env, only: dp => real64
  implicit none

  type :: vector3
    real(dp) :: x = 0.0_dp, y = 0.0_dp, z = 0.0_dp     ! default initialization
  end type vector3

  type :: particle
    character(len=:), allocatable :: name
    real(dp) :: mass = 1.0_dp
    type(vector3) :: pos, vel                           ! nested types
    real(dp), allocatable :: history(:)                 ! allocatable component
  end type particle

end module particles

program demo
  use particles
  implicit none
  type(particle) :: p
  type(particle), allocatable :: swarm(:)

  p = particle(name="electron", mass=9.109e-31_dp, pos=vector3(1, 0, 0), vel=vector3())  ! structure constructor
  p%pos%y = 2.0_dp                                      ! component access with %
  print *, p%name, p%mass, p%pos

  allocate(swarm(100))
  swarm%mass = 2.0_dp                                   ! component of an array of types
  print *, sum(swarm%mass)
end program demo

16.2 Assignment & copying

Intrinsic assignment copies all components (deep-copying allocatable components, shallow-copying pointers).

16.3 Private components & sequence/bind

type :: account
  private
  real :: balance = 0.0
  character(len=:), allocatable, public :: owner
end type account

type, bind(c) :: c_point     ! C-compatible layout (§25)
  real(c_double) :: x, y
end type c_point

16.4 Procedures operating on types

Type-bound procedures and operator overloading turn these into OOP (§22–23).

pure function add_vec(a, b) result(c)
  type(vector3), intent(in) :: a, b
  type(vector3) :: c
  c = vector3(a%x + b%x, a%y + b%y, a%z + b%z)
end function add_vec