Introduction
In programming, data structures are the foundation for storing and managing information.
In the Go programming language, three of the most commonly used data structures are Array, Slice, and Map.
In this article, we’ll go through:
- What an Array is in Go
- How Slice works
- Using Map for key-value storage
- Simple code examples
1. Array in Go
An array is a collection of elements with a fixed size.
All elements must have the same data type.
Example:
package main
import "fmt"
func main() {
// declare an array with length 3
var numbers [3]int
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
fmt.Println("Array content:", numbers)
// array with direct initialization
fruits := [3]string{"Apple", "Mango", "Orange"}
fmt.Println("Fruit array:", fruits)
}
Output
Array content: [10 20 30]
Fruit array: [Apple Mango Orange]
⚠️ Limitation: Once an array is defined, its size cannot be changed.
2. Slice in Go
Slices in Go are more flexible than arrays because their length is dynamic.
You can think of a slice as a view of an underlying array.
You don’t need to define the size in advance.
Example:
package main
import "fmt"
func main() {
// Create a slice directly
numbers := []int{1, 2, 3, 4, 5}
fmt.Println("Numbers:", numbers)
// Slicing from an array
arr := [5]int{10, 20, 30, 40, 50}
slice := arr[1:4] // elements at index 1, 2, 3
fmt.Println("Slice from array:", slice)
// Append new elements
numbers = append(numbers, 6, 7)
fmt.Println("After append:", numbers)
// Get length and capacity
fmt.Println("Length:", len(numbers))
fmt.Println("Capacity:", cap(numbers))
}
Output
Numbers: [1 2 3 4 5]
Slice from array: [20 30 40]
After append: [1 2 3 4 5 6 7]
Length: 7
Capacity: 10
✨ Note: Slice is powerful because it can grow dynamically and supports slicing operations.
3. Map in Go
A map is a key-value data structure, similar to a dictionary in Python or an object in JavaScript.
Example
package main
import "fmt"
func main() {
// declare a map with string keys and int values
ages := map[string]int{
"Ana": 21,
"Budi": 25,
"Cici": 19,
}
fmt.Println("Age data:", ages)
// access value by key
fmt.Println("Budi's age:", ages["Budi"])
// add new data
ages["Dedi"] = 30
fmt.Println("After adding Dedi:", ages)
// delete data
delete(ages, "Ana")
fmt.Println("After deleting Ana:", ages)
}
Output
Age data: map[Ana:21 Budi:25 Cici:19]
Budi's age: 25
After adding Dedi: map[Ana:21 Budi:25 Cici:19 Dedi:30]
After deleting Ana: map[Budi:25 Cici:19 Dedi:30]
💡 Tip: Map is very useful when you need to store data with unique identifiers.
Conclusion
- Array → fixed size, not commonly used directly.
- Slice → flexible, supports append and slicing.
- Map → great for key-value storage.
These three are the basic building blocks in Go.
Top comments (0)