In Go, collections allow us to store 0, 1, or many of another type. There are three main types of collection:
var numbers [5]int
numbers[0] = 10
numbers[1] = 20
// Or initialize with values
scores := [3]int{95, 87, 92}
You can think of arrays as a fixed-size list of items. Once you declare an array with a specific size (like [5]int), that size cannot change. Arrays are useful when you know exactly how many elements you need and that number won't change during your program's execution.
// Accessing array elements
fmt.Println(scores[0]) // Prints: 95
fmt.Println(scores[2]) // Prints: 92
var names []string
names = append(names, "Alice")
names = append(names, "Bob")
// Or initialize with values
fruits := []string{"apple", "banana", "orange"}
// You can also create a slice from an array
slice := scores[0:2] // Takes first 2 elements from scores array
Slices are similar to arrays but with one key difference: they have a dynamic size. You can add or remove elements as needed using functions like append(). Slices are the most commonly used collection type in Go because of their flexibility.
// Growing a slice dynamically
fruits = append(fruits, "mango", "strawberry")
fmt.Println(len(fruits)) // Prints: 5
// Create a map with string keys and int values
ages := make(map[string]int)
ages["Alice"] = 30
ages["Bob"] = 25
// Or initialize with values
capitals := map[string]string{
"USA": "Washington D.C.",
"Japan": "Tokyo",
"France": "Paris",
}
// Access a value
fmt.Println(ages["Alice"]) // Prints: 30
Maps are key-value pairs, similar to dictionaries in Python or objects in JavaScript. They allow you to store data where each value is associated with a unique key. Maps are great when you need to look up values quickly by a specific identifier.
// Looking up values in a map
capital := capitals["Japan"]
fmt.Println(capital) // Prints: Tokyo
// Check if a key exists
capital, exists := capitals["Germany"]
if exists {
fmt.Println(capital)
} else {
fmt.Println("Capital not found")
}
For this challenge, create two different collection types:
Slice: Create a slice of strings called names which should contain 3 names: "Goku", "Vegeta", and "Gohan" in that exact order
Map: Create a map called powerLevels that maps character names (strings) to their power levels (unsigned integers). Include the following entries:
Once created, print out:
names slicepowerLevels map