Introduction
Data types play a crucial role in programming languages like Go, as they define the nature and range of values that variables can hold. In this article, we'll delve into the fundamentals of data types in Go, exploring boolean, numeric, and string types along with their usage and examples.
Basic Data Types in Go
Boolean Data Type
The boolean data type represents two values:
true
orfalse
.It's declared using the
bool
keyword.The default value for a boolean variable is
false
.
package main
import "fmt"
func main() {
var b1 bool = true
var b2 = true
var b3 bool
b4 := true
fmt.Println(b1) // true
fmt.Println(b2) // true
fmt.Println(b3) // false
fmt.Println(b4) // true
}
Integer Data Types
Integers are used to store whole numbers without decimals.
Go provides signed and unsigned integer types with varying sizes.
Signed integers (
int
) can store both positive and negative values, while unsigned integers (uint
) can store only non-negative values.
package main
import "fmt"
func main() {
var x int = 500
var y int = -4500
fmt.Printf("Type: %T, value: %v\n", x, x)
fmt.Printf("Type: %T, value: %v\n", y, y)
}
Float Data Types
Floats are used to represent numbers with decimal points.
Go offers
float32
andfloat64
data types for representing floating-point numbers.Float64 is the default type for floating-point values.
package main
import "fmt"
func main() {
var x float32 = 123.78
var y float32 = 3.4e+38
fmt.Printf("Type: %T, value: %v\n", x, x)
fmt.Printf("Type: %T, value: %v\n", y, y)
}
String Data Type
Strings are sequences of characters enclosed within double quotes.
Go's
string
data type is used to store textual data.String variables can be declared using the
string
keyword.
package main
import "fmt"
func main() {
var txt1 string = "Hello!"
var txt2 string
txt3 := "World 1"
fmt.Printf("Type: %T, value: %v\n", txt1, txt1)
fmt.Printf("Type: %T, value: %v\n", txt2, txt2)
fmt.Printf("Type: %T, value: %v\n", txt3, txt3)
}
Choosing the Right Data Type
When declaring variables, it's essential to choose the appropriate data type based on the range and nature of values they will hold. Using the wrong data type may lead to errors or unexpected behavior in your program.
Conclusion
Understanding data types is fundamental to writing efficient and error-free code in Go. By mastering data types like boolean, numeric, and string, you gain better control over variable declaration and manipulation, leading to more robust and reliable programs. Happy coding in Go!