Basic Types in Go
In the realm of Go programming, understanding basic types is akin to mastering the alphabet of a new language. Go, designed for simplicity and efficiency, provides a set of fundamental types to represent various kinds of data. In this chapter, we will explore the basic types in Go, grouping them by categories and shedding light on their characteristics, including the unique concept of runes.
Numeric Types
Integers (int
, int8
, int16
, int32
, int64
)
Integers represent whole numbers, both positive and negative, without any decimal points.
package main
import "fmt"
func main() {
var age int = 25
fmt.Println(age)
}
Range of Integers
int8
: -128 to 127int16
: -32,768 to 32,767int32
: -2,147,483,648 to 2,147,483,647int64
: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Floating-Point Numbers (float32
, float64
)
Floating-point numbers represent real numbers with decimal points.
package main
import "fmt"
func main() {
var pi float64 = 3.14
fmt.Println(pi)
}
Range of Floating-Point Numbers
float32
: Approximately -3.4e38 to 3.4e38, with about 7 decimal digits of precisionfloat64
: Approximately -1.7e308 to 1.7e308, with about 15 decimal digits of precision
Complex Numbers (complex64
, complex128
)
Complex numbers have both real and imaginary parts.
package main
import "fmt"
func main() {
var z complex128 = complex(1, 2)
fmt.Println(z)
}
Boolean and Character Types
Booleans (bool
)
Booleans are binary values representing true or false.
package main
import "fmt"
func main() {
var isTrue bool = true
fmt.Println(isTrue)
}
Strings (string
)
Strings are sequences of characters.
package main
import "fmt"
func main() {
message := "Hello, Go!"
fmt.Println(message)
}
Rune (rune
)
A rune represents a Unicode code point, commonly used to represent characters.
package main
import "fmt"
func main() {
var letter rune = 'A'
fmt.Printf("%c\n", letter)
}
Range of Runes
- A rune is a 32-bit integer representing a Unicode code point.
Byte Type
Byte (byte
, uint8
)
A byte is an alias for uint8
and represents a sequence of 8 bits, often used when dealing with binary data.
package main
import "fmt"
func main() {
var b byte = 65
fmt.Printf("%c\n", b)
}
Range of Byte
byte
is an alias foruint8
, and its range is from 0 to 255.
Conclusion
Understanding the basic types in Go is foundational to writing robust and expressive code. Whether you’re dealing with integers, floating-point numbers, booleans, strings, runes, bytes, or complex numbers, having a solid grasp of these fundamental types is essential.
As you embark on your Go programming journey, let these basic types be your allies in crafting elegant and efficient solutions to a myriad of problems. Happy coding!