Welcome to our deep dive into Go (Golang) Data Types! This tutorial is designed for both beginners and intermediates, so let's get started. 📝
Data types are categories that define what kind of data a variable can hold. Go supports several data types:
bool)int, float64)string)Booleans are used to represent true or false values. They are essential when making decisions in our programs.
// Declaring a boolean variable
isStudent := true
// Using boolean in an if statement
if isStudent {
fmt.Println("Welcome, student!")
} else {
fmt.Println("Welcome, visitor!")
}Go supports several numeric types, including:
int8, int16, int32, int64)float32, float64)// Declaring numeric variables
var age int = 23
var pi float64 = 3.14159
// Performing calculations
total := age + int(pi)Strings in Go are sequences of bytes representing text. They are defined using single or double quotes.
// Declaring a string variable
name := "John Doe"
// Accessing string characters
fmt.Println(name[0]) // Output: JArrays are fixed-size collections of elements of the same data type.
// Declaring an array
var numbers [5]int
// Initializing an array
numbers = [5]int{1, 2, 3, 4, 5}
// Accessing array elements
fmt.Println(numbers[1]) // Output: 2Slices are more flexible than arrays as they can grow and shrink in size.
// Declaring a slice
var slices []int
// Creating a slice
slices = []int{1, 2, 3, 4, 5}
// Accessing slice elements
fmt.Println(slices[1]) // Output: 2Structs are user-defined data types that let you group related variables together.
// Declaring a struct
type Person struct {
Name string
Age int
}
// Creating a struct variable
john := Person{Name: "John Doe", Age: 23}
// Accessing struct fields
fmt.Println(john.Name) // Output: John DoeWhat is the output of `fmt.Println(numbers[1])` in the "Arrays" example above?
This lesson is just a starting point for understanding Go data types. In the next lessons, we will dive deeper into each data type, explore real-world examples, and practice coding exercises to help you master Golang. 💡
Stay tuned and happy coding! 🚀