# README
Type Definition
Type Definition allows us create our own types in Go.
This program aims to demonstrate what defined types are and how to create them. It also explains underlying types and aliased.
Explanation
Defined Types
Go allows us to create our own types using Type Definition. These created types which aren't Predefined(e.g. int, float, bool) are known as Defined Types.
An example is the Duration type defined in the time. package.
It is defined using the syntax type Duration int64
.
Here, Duration
is the name of the new type based on int64. int64
represents the Underlying Type.
- Defined Types ensures Type Safety i.e. they cannot be used with other types without doing a type conversion.
- Methods can be attached to Defined Types as in the time.Duration package.
- Values of a defined type can be converted to another type if that type's underlying type is identical.
Underlying Types
Underlying Types are used to define the structure of a new type. Take the example below:
type Duration int64
type MyDuration Duration
type MoreDuration MyDuration
In the declarations above, int64
is the Underlying type for the Defined Types Duration
, MyDuration
, and MoreDuration
.
These types have a representation of signed integers and a byte size of 8 which they all get from int64
.
- A defined type shares the same underlying type with its source type. Ex.
MoreDuration
shares the same underlying typeint64
asMyDuration
. - Types with identical underlying types can be converted to each other. Ex.
MyDuration
can be converted toDuration
andDuration
can be converted toMoreDuration
.
Note: We can deduce from the above that there are no type hierarchies in Go.
Aliased Types
These are the very same types with a new name.
Example
byte
anduint8
are exactly the same types with different names.rune
andint32
are also exactly the same types with different names.
- Aliased Types can be used together without type conversions.
- Aliased Types can be represented as:
type byte = uint8
type rune = int32
Rune is used for representing unicode characters.
Run Program
$ go run main.go definedtypes.go underlyingtypes.go