What are derived data types in Fortran?

Image link here.

Overview

In Fortran, you can define your data types. This is what derived data types are all about. Derived data types are also called structures in Fortran. Derived data types make it easy to create a particular structure of your choice.

Syntax

type [name of derived data type]
  [some declarations]
end type [name of derived data type]
  • [name of derived data type]: This is the name of the derived data type that you want to create. Examples are User, School, Account, etc.

  • [some declarations]: This is where you declare the data types for the fields of your structure.

How to create a derived data type

You can create a derived data type in two steps:

  • Define the derived data type.
  • Create an object of the derived data type.

You can create an object with the method below:

type([name of derived data type]) :: [name of structure]

!Example
type(User) :: user1

Code

In the following example, we create a derived data type, create an object, populate it with the required values, and then display its values.

program derivedDataTypes

!create derivedDataType
type User
   character(len = 50) :: name
   character(len = 1) :: gender
   character(len = 50) :: role
end type User

!create structure
type(User) :: user1

!give structure values
user1%name = "John Doe"
user1%gender = "M"
user1%role = "Network Administrator"

!print structure values
print *, user1%name
print *, user1%gender
print *, user1%role


end program derivedDataTypes

When the code above is run, it will print the following:

John Doe
M
Network Administrator