Data types in Go define the type of values that can be stored in variables. Understanding data types is crucial for writing efficient and error-free code. In this chapter, we will cover basic to advanced data types in Go, along with examples to clarify concepts.
Integers in Go represent whole numbers without a fractional component. The size of an integer type determines its range of values.
int
: This is the default integer type whose size varies depending on the underlying architecture.int8
, int16
, int32
, int64
: These are signed integer types with explicit bit sizes, ranging from 8 to 64 bits.
package main
import "fmt"
func main() {
var num int = 10
fmt.Println(num)
}
Floating-point types in Go represent numbers with a fractional component. They are used when precise decimal values are required.
float32
, float64
: These are floating-point types with different precisions, where float64
offers higher precision than float32
.
package main
import "fmt"
func main() {
var num float64 = 3.14
fmt.Println(num)
}
Booleans in Go represent true or false values. They are primarily used in control flow and logical operations.
bool
: This is the boolean type in Go.
package main
import "fmt"
func main() {
var isTrue bool = true
fmt.Println(isTrue)
}
Strings in Go represent sequences of characters. They are used extensively in handling text and messages.
string
: This is the string type in Go, represented by double quotes.
package main
import "fmt"
func main() {
var message string = "Hello, World!"
fmt.Println(message)
}
Arrays in Go are fixed-size collections of items of the same type. The size of the array is fixed at compile time.
package main
import "fmt"
func main() {
var numbers [3]int = [3]int{1, 2, 3}
fmt.Println(numbers)
}
Slices in Go are dynamic arrays with a flexible size. They are more commonly used than arrays due to their flexibility.
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3}
fmt.Println(numbers)
}
Maps in Go are collections of key-value pairs where keys and values can be of any type. They are used for fast lookups and indexing.
package main
import "fmt"
func main() {
ages := map[string]int{
"Alice": 30,
"Bob": 25,
}
fmt.Println(ages)
}
Structs in Go are user-defined types that group together variables of different types. They are used to create complex data structures.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
person := Person{Name: "Alice", Age: 30}
fmt.Println(person)
}
Understanding data types in Go is fundamental for writing efficient and reliable programs. By mastering the basic and composite data types along with their usage, developers can manipulate data effectively and build robust applications. It's crucial to choose the appropriate data type for variables to ensure clarity and efficiency in code. With this knowledge, you'll be well-equipped to tackle a wide range of programming challenges in Go. Happy coding !❤️