In Go, it is possible to bind a type to an identifier to create a new named type that can be referenced and used wherever the type is needed. Declaring a type takes the general format as follows:
type <name identifier> <underlying type name>
The type declaration starts with the keyword type
followed by a name identifier and the name of an existing underlying type. The underlying type can be a built-in named type such as one of the numeric types, a Boolean, or a string type as shown in the following snippet of type declarations:
type truth bool type quart float64 type gallon float64 type node string
A type declaration can also use a composite type literal as its underlying type. Composite types include array, slice, map, and struct. This section focuses on non-composite types. For further details on composite types, refer to Chapter 7, Composite Types.
The following sample illustrates how named types work in their most basic forms. The code in the example converts temperature values. Each temperature unit is represented by a declared type including fahrenheit
, celsius
, and kelvin
.
package main import "fmt" type fahrenheit float64 type celsius float64 type kelvin float64 func fharToCel(f fahrenheit) celsius { return celsius((f - 32) * 5 / 9) } func fharToKel(f fahrenheit) celsius { return celsius((f-32)*5/9 + 273.15) } func celToFahr(c celsius) fahrenheit { return fahrenheit(c*5/9 + 32) } func celToKel(c celsius) kelvin { return kelvin(c + 273.15) } func main() { var c celsius = 32.0 f := fahrenheit(122) fmt.Printf("%.2f u00b0C = %.2f u00b0K ", c, celToKel(c)) fmt.Printf("%.2f u00b0F = %.2f u00b0C ", f, fharToCel(f)) }
golang.fyi/ch04/typedef.go
In the preceding code snippet, the new declared types are all based on the underlying built-in numeric type float64
. Once the new type has been declared, it can be assigned to variables and participate in expressions just like its underlying type. The newly declared type will have the same zero-value and can be converted to and from its underlying type.
18.224.44.53