Go is a statically typed programming language. This means that variables always have a specific type and that type cannot change. Static typing may seem cumbersome at first. You’ll spend a large amount of your time just trying to fix your program so that it finally compiles. But types help us reason about what our program is doing and catch a wide variety of common mistakes.
Go comes with several built-in data types which we will now look at in more detail.
Numbers
Go has several different types to represent numbers. Generally we split numbers into two different kinds: integers and floating-point numbers.
Integers
Integers are basically numbers without a decimal component. In Go the integers are represented as following types, uint8
, uint16
, uint32
, uint64
, int8
, int16
, int32
and int64.
8, 16, 32 and 64 tell us how many bits each of the types use. uint
means “unsigned integer” while int
means “signed integer”. Unsigned integers only contain positive numbers (or zero).
Simply if you are working with integers then you are free to use int
, and if you wish to optimize further and aware of maximum bit required then you can specify the bit size like int8
or int16
Let us take an example of int
addition.
Floating point numbers
Floating point numbers are numbers that contain a decimal component (real numbers). (5.432, 0.456, 0.0000768). Like we discussed for integers floating point numbers have a certain size (32 bit or 64 bit). Using a larger sized floating point number increases its precision. (how many digits it can represent). In addition to numbers float can represent some other values like “not a number — NaN
” or positive and negative infinity. (+∞
and −∞
).
Go has two floating point types: float32
and float64
(also often referred to as single precision and double precision respectively) as well as two additional types for representing complex numbers (numbers with imaginary parts): complex64
and complex128
. Generally we use float64
when working with floating point numbers for better precision in calculations.
Let us take an example of float
addition.
Strings
In general the strings are a sequence of characters with a definite length used to represent text. Go strings are made up of individual bytes, usually one for each character (there is some exception for other languages).
String literals can be created using double quotes "Hello World"
or single quotes 'Hello World'
or backticks `Hello World`
. The difference between these is that double quoted strings and single quoted strings cannot contain newlines and they allow special escape sequences. For example \n
gets replaced with a newline and \t
gets replaced with a tab character.
Let us consider some example about common operations with strings.
Boolean
A boolean value is a special 1 bit integer type used to represent true and false (or on and off). Three logical operators are used with boolean values: && (and), || (or), ! (not).