This lesson's topic is working with Maps and Sorting in Go. Learning to access map data in order enriches our toolkit for organized and efficient data manipulation.
Go's sort
package helps us access map data in a sorted fashion. To illustrate, we create a map and use slices to sort keys, allowing us to display map values in order.
One approach we can take is to extract all keys int a slice, sort this slice, and print the values in a natural order (alphabetically). Here's an example:
Go1package main 2 3import ( 4 "fmt" 5 "sort" 6) 7 8func main() { 9 // Map with fruits as keys and corresponding counts as values 10 fruitCounts := map[string]int{ 11 "banana": 3, 12 "apple": 4, 13 "pear": 1, 14 "orange": 2, 15 } 16 17 // Extract and sort keys 18 keys := make([]string, 0, len(fruitCounts)) 19 for key := range fruitCounts { 20 keys = append(keys, key) 21 } 22 sort.Strings(keys) 23 24 // Print fruits in sorted order by keys 25 for _, key := range keys { 26 fmt.Printf("%s=%d\n", key, fruitCounts[key]) 27 } 28}
The output will be:
1apple=4 2banana=3 3orange=2 4pear=1
Using slices to sort keys, we can implement functionalities for map operations like existence checks and removals, accessing elements in a sorted order:
Go1package main 2 3import ( 4 "fmt" 5 "sort" 6) 7 8func main() { 9 // Initialize the map 10 fruitCounts := map[string]int{ 11 "banana": 3, 12 "apple": 4, 13 "pear": 1, 14 "orange": 2, 15 } 16 17 // Check existence 18 if _, exists := fruitCounts["apple"]; exists { 19 fmt.Println("Contains 'apple' key: True") 20 } 21 22 // Remove an element 23 delete(fruitCounts, "apple") 24 if _, exists := fruitCounts["apple"]; !exists { 25 fmt.Println("Removed 'apple': True") // Output: True 26 } 27 28 // Fetch non-existent key 29 value, exists := fruitCounts["apple"] 30 if !exists { 31 fmt.Println("Value: Not found") // Output: Value: Not found 32 } else { 33 fmt.Printf("Value: %d\n", value) 34 } 35 36 // Find and display the last element in sorted key order 37 keys := make([]string, 0, len(fruitCounts)) 38 for key := range fruitCounts { 39 keys = append(keys, key) 40 } 41 sort.Strings(keys) 42 lastKey := keys[len(keys)-1] 43 fmt.Printf("Last entry: %s=%d\n", lastKey, fruitCounts[lastKey]) // Output: pear=1 44}
You've explored how to sort access in Go using regular maps. This included extracting and sorting keys with the sort
package to access map values in order, and performing essential operations. Continue practicing to deepen your understanding of maps and sorting in Go.