In this chapter, we will discuss the forms of data in the Go programming language.
Go is statically typed. This means that once a variable is assigned to have a certain data type, it can’t be assigned any other type. In most programming languages, this assignment of the type is done explicitly, by writing down the type of the variable. In Go, there is the concept of inference, meaning we can provide the concrete type - but don’t have to.
Based on the type of the value, Go will infer the data type of the variable.
In Go, the data type is written after the variable name. This is in contrast to most programming languages.
Basic types
All of these types can be used to describe variables:
- bool
- string
- int
- int8, int16, int32, int64
- uint, unit8 …, unintptr
- byte (is the same as uint8)
- rune (is the same as int32)
- float32, float64
- complex64, complex128
By default, int
, uint
and uintptr
are 32-bit on 32-bit systems and 64-bit on 64-bit systems.
Zero values
When initializing an “empty” variable, the variable will hold a so-called zero value.
- 0 for numeric types
- false of boolean
- "" (empty string) for strings
Type conversion
Basically, T(v)
converts value v
to the type T
. E. g:
In our example, we turned the integer into a float.
Assignment between different types always needs explicit conversion.
- Types can be inferred, meaning there is no need to explicitly mention the type of a variable:
Signed and unsigned values
A signed value can represent both negative and positive values. On the other hand, there are unsigned values, that only represent positive values.
Only integers can be differentiated between signed and unsigned in Go. Unsigned integers of different sizes are created by using a u
as the first letter, e. g. uint
, uint32
, uint64
etc.
Here are some examples:
Next chapter: Variables