In Golang, an integer is a data type used to represent whole numbers. This data type allows us to work with whole numbers without decimals, such as counting the quantity of items or indices in a list. There are two main categories of integers in Golang: unsigned integers and signed integers.
Unsigned Integer
In Golang, the term "unsigned" is used to refer to an integer data type that only stores non-negative values (zero and positive numbers) and does not provide space to store negative values. Unsigned integer data types are denoted as "uint" (unsigned integer).
Here is a cheat sheet of the usage of unsigned integer data types in Golang.
Data Type Name | Bit Size | Value Range |
uint8 | 8 | 0 until 255 |
uint16 | 16 | 0 until 65535 |
uint32 | 32 | 0 until 4294967295 |
uint64 | 64 | 0 until 18446744073709551615 |
Unsigned Integer Code Example
(file main.go):
package main
import "fmt"
func main() {
var number8 uint8
number8 = 20
fmt.Println(number8)
}
We can see that if we run it with:
go run main.go
Then it will produce
20
Signed Integer
In Golang, the term "integer" can represent a signed integer, which is a whole number that includes both positive and negative values.
Here is a cheat sheet of the usage of signed integer data types in Golang.
Data Type Name | Bit Size | Value Range |
int8 | 8 | 0 until 255 |
int16 | 16 | 0 until 65535 |
int32 | 32 | 0 until 4294967295 |
int64 | 64 | 0 until 18446744073709551615 |
Contoh Kode Signed Integer
(file main.go):
package main
import "fmt"
func main() {
var number8 int8
number8 = 20
fmt.Println(number8)
}
We can see that if we run it with:
go run main.go
Then it will produce
20