Variable Types in Go
Basic Variable Types
In Go, variables are strongly typed and provide a robust way to store and manipulate data. Understanding the basic variable types is crucial for effective programming. Let's explore the fundamental types:
Numeric Types
Go offers several numeric types to represent different kinds of numbers:
Type |
Description |
Range |
int |
Integer |
Platform-dependent |
int8 |
8-bit integer |
-128 to 127 |
int16 |
16-bit integer |
-32,768 to 32,767 |
int32 |
32-bit integer |
-2³¹ to 2³¹-1 |
int64 |
64-bit integer |
-2⁶³ to 2⁶³-1 |
uint |
Unsigned integer |
0 to platform max |
Floating-Point Types
package main
import "fmt"
func main() {
// Floating-point type examples
var floatA float32 = 3.14
var floatB float64 = 3.14159265359
fmt.Printf("float32: %f\n", floatA)
fmt.Printf("float64: %f\n", floatB)
}
Complex Types
String Type
Strings in Go are immutable sequences of characters:
package main
import "fmt"
func main() {
var message string = "Hello, LabEx!"
fmt.Println(message)
}
Boolean Type
Represents true or false values:
package main
import "fmt"
func main() {
var isActive bool = true
fmt.Println(isActive)
}
Composite Types
Arrays
Fixed-size collections of elements:
package main
import "fmt"
func main() {
// Array declaration
var numbers [5]int = [5]int{1, 2, 3, 4, 5}
fmt.Println(numbers)
}
Slices
Dynamic and more flexible than arrays:
package main
import "fmt"
func main() {
// Slice declaration
fruits := []string{"apple", "banana", "cherry"}
fmt.Println(fruits)
}
Type Inference
Go supports type inference, allowing automatic type detection:
package main
import "fmt"
func main() {
// Type inference
name := "LabEx" // Inferred as string
age := 25 // Inferred as int
fmt.Printf("Name: %s, Age: %d\n", name, age)
}
Zero Values
Each type has a default zero value:
graph TD
A[Numeric Types] --> B[0]
A --> C[Floating Point] --> D[0.0]
A --> E[Boolean] --> F[false]
A --> G[String] --> H["" (empty string)]
A --> I[Pointer] --> J[nil]
By understanding these variable types, you'll have a solid foundation for writing efficient Go programs in various scenarios.