Data Types
Introduction
Go is statically typed, meaning variables always have a specific type and that type cannot change.
Data Type for a variable defines:
The amount of memory space allocated for variables.
A data type specifies the possible values for variables.
The operations that can be performed on variables.
Go built-in data types:
Numbers
Boolean
String
Integer
Signed integers
Type | Size | Description (Two's complement) |
int8 | 8 bits | 8 bit signed integer |
int16 | 16 bits | 16 bit signed integer |
int32 | 32 bits | 32 bit signed integer |
int64 | 64 bits | 64 bit signed integer, can also be represented in octal and hexadecimal |
int | Platform dependent | signed integers of at least 32-bit in size, not equivalent to int32. |
Unsigned integers
Type | Size | Description (Two's complement) |
uint8 | 8 bits | 8 bit unsigned integer |
uint16 | 16 bits | 16 bit unsigned integer |
uint32 | 32 bits | 32 bit unsigned integer |
uint64 | 64 bits | 64 bit unsigned integer |
uint | Platform dependent | unsigned integers of at least 32-bit in size, not equivalent to int32. |
Use int unless for specific reasons for others. Integral types have default value of 0. Octal numbers can be declared using prefix and hexadecimal using the 0x prefix.
Other integer types
Type | Description (Two's complement) |
byte | It is alias for and equivalent to uint8 |
rune | It is alias for and equivalent to int32, used to represent characters. |
uintptr | It is used to hold memory address pointers |
Golang does not support a char data type, instead it has byte and rune to represent character values. This helps to distinguish characters from integer values. byte data type is represented with a ASCII value and the rune data type is represented with Unicode value encoded in UTF-8 format.
Float
Go supports float32 and float64 represented with 32-bit and 64-bit in memory respectively.
Complex Numbers
Go supports complex64 and complex128. Each of the type uses float32 and float64 respectively, to represent their real and imaginary parts.
Boolean
String
Type Conversions
Syntax: The expression T(v)
converts the value v
to the type T
.
T(v)
converts the value v
to the type T
.Type Inference
When declaring a variable without specifying an explicit type (either by using the :=
syntax or var =
expression syntax), the variable's type is inferred from the value on the right hand side.
Last updated