Integer Basics
What Are Integers?
In Golang, integers are whole numbers that can be positive, negative, or zero. Unlike floating-point numbers, integers do not have decimal points. Go provides several integer types to accommodate different ranges and memory requirements.
Integer Type Categories
Golang offers two main categories of integer types:
graph TD
A[Integer Types] --> B[Signed Integers]
A --> C[Unsigned Integers]
B --> D[int8, int16, int32, int64]
C --> E[uint8, uint16, uint32, uint64]
Signed Integers
Signed integers can represent both positive and negative numbers:
Type |
Size (bits) |
Range |
int8 |
8 |
-128 to 127 |
int16 |
16 |
-32,768 to 32,767 |
int32 |
32 |
-2^31 to 2^31 - 1 |
int64 |
64 |
-2^63 to 2^63 - 1 |
Unsigned Integers
Unsigned integers can only represent non-negative numbers:
Type |
Size (bits) |
Range |
uint8 |
8 |
0 to 255 |
uint16 |
16 |
0 to 65,535 |
uint32 |
32 |
0 to 2^32 - 1 |
uint64 |
64 |
0 to 2^64 - 1 |
Go also provides platform-dependent integer types:
int
: Typically 32 bits on 32-bit systems, 64 bits on 64-bit systems
uint
: Unsigned version of int
uintptr
: Large enough to store a pointer value
Code Example
Here's a simple demonstration of integer types in Go:
package main
import "fmt"
func main() {
var smallInt int8 = 127
var mediumInt int32 = 2147483647
var largeInt int64 = 9223372036854775807
fmt.Printf("Small Integer: %d\n", smallInt)
fmt.Printf("Medium Integer: %d\n", mediumInt)
fmt.Printf("Large Integer: %d\n", largeInt)
}
Key Takeaways
- Choose integer types based on the expected range of values
- Be mindful of potential overflow
- Use the smallest type that can accommodate your data
- Consider memory efficiency when selecting integer types
By understanding these basics, you'll be well-prepared to make informed decisions about integer type selection in your LabEx Go programming projects.