Understanding data types is fundamental to programming as they define the kind of values a variable can hold and its size. In Go, this concept is critical because the language is statically typed. Once a variable’s type is set, it can only contain values of that type.
Basic Data Types in Go
Go provides three primary types of data:
- Boolean (
bool
)
A Boolean data type stores logical values. It can hold eithertrue
orfalse
. - Numeric
This category includes:- Integer types: Whole numbers such as 10 or -45.
- Floating point types: Decimal numbers like 3.14 or -0.987.
- Complex types: Represents numbers with both real and imaginary parts.
- String (
string
)
String data types are used for text values. They are sequences of characters like"Hello"
or"GoLang Rules!"
.
Example of Go Data Types
The example below demonstrates how various data types can be used in a Go program:
package main import ("fmt") func main() { var isRunning bool = true // Boolean var topSpeed int = 300 // Integer var engineCapacity float32 = 1.5 // Floating point number var bikeBrand string = "Yamaha" // String fmt.Println("Running Status: ", isRunning) fmt.Println("Top Speed: ", topSpeed) fmt.Println("Engine Capacity: ", engineCapacity) fmt.Println("Brand: ", bikeBrand) }
Output:
Running Status: true Top Speed: 300 Engine Capacity: 1.5 Brand: Yamaha