Section 3 of 12
Arrays, Slices & Maps
Learn collection types for storing and organizing data
Course Progress
Section 3 of 1225% complete
Tutorials
Arrays
Arrays are fixed-size collections of elements of the same type.
Code Examples
Array Basicsgo
package main
import "fmt"
func main() {
// Array with fixed size
var arr [5]int
arr[0] = 1
arr[1] = 2
// Array initialization
names := [3]string{"Alice", "Bob", "Charlie"}
// Get array length
fmt.Println(len(names))
// Iterate
for i, name := range names {
fmt.Printf("%d: %s\n", i, name)
}
}Slices
Slices are dynamic, flexible views into arrays. They're more commonly used than arrays in Go.
Code Examples
Slice Operationsgo
package main
import "fmt"
func main() {
// Create slice
var slice []int
slice = append(slice, 1, 2, 3)
// Slice literal
numbers := []int{10, 20, 30, 40, 50}
// Slicing
sub := numbers[1:4] // [20, 30, 40]
fmt.Println(sub)
// Make with capacity
s := make([]string, 0, 5)
s = append(s, "Go", "is", "awesome")
fmt.Println(s, len(s), cap(s))
// Copy
dest := make([]int, len(numbers))
copy(dest, numbers)
}Maps
Maps are unordered collections of key-value pairs, similar to dictionaries or hash maps.
Code Examples
Map Basicsgo
package main
import "fmt"
func main() {
// Map literal
ages := map[string]int{
"Alice": 25,
"Bob": 30,
"Charlie": 35,
}
// Access
fmt.Println(ages["Alice"])
// Add/Update
ages["David"] = 40
// Delete
delete(ages, "Bob")
// Check if key exists
age, exists := ages["Alice"]
if exists {
fmt.Println("Age:", age)
}
// Iterate
for name, age := range ages {
fmt.Printf("%s: %d\n", name, age)
}
}Exercises
Student Grade Tracker
Use a map to store student names and grades, then calculate the average
INTERMEDIATEStarter Code:
package main
import "fmt"
func main() {
grades := map[string]int{
"Alice": 95,
"Bob": 87,
"Charlie": 92,
}
// TODO: Calculate average grade
// TODO: Print average and all grades
}Hands-on Project
Contact Management System
Build a simple contact management system using maps and slices
INTERMEDIATE
Learning Objectives
- >Use maps and slices together
- >Add/remove items
- >Search and filter data
Project Tips
- > Start by understanding the requirements
- > Break the project into smaller tasks
- > Test your code frequently as you build
- > Add error handling throughout your code
- > Consider edge cases and validate inputs
- > Document your code with comments