Solution 1: Composite Data Types
Let’s solve the challenges set in the previous lesson.
We'll cover the following...
Problem 1: Solution
Here’s a sample Go program that converts a 2D array into a map:
package mainimport "fmt"func convertToMap(arr [][]string) map[string]string {m := make(map[string]string)for _, pair := range arr {m[pair[0]] = pair[1]}return m}func main() {arr := [][]string{{"key1", "value1"}, {"key2", "value2"}, {"key3", "value3"}}mp := convertToMap(arr)fmt.Println(mp)}
Code explanation
Lines 5–11: The
convertToMapfunction iterates over each pair in the 2D array using aforloop, assigning the first element of the pair as the key and the second element as the value in the mapm. Finally, it returns the resulting map.Lines 13–17: The
mainfunction creates a 2D array of key-value pairs,arr, passes it to theconvertToMapfunction to get a map of key-value pairsmp, and prints the resulting map to the console using thefmt.Printlnfunction.
Following is the output of the code above:
map[key1:value1 key2:value2 key3:value3]
Problem 2: Solution
Here’s a sample Go program to convert a map into two slices:
package mainimport "fmt"func extractKeysAndValues(inputMap map[string]int) ([]string, []int) {var keys []stringvar values []intfor key := range inputMap {keys = append(keys, key)values = append(values, inputMap[key])}return keys, values}func main() {originalMap := map[string]int{"first": 1,"second": 2,"third": 3,}keys, values := extractKeysAndValues(originalMap)fmt.Println("Keys:", keys)fmt.Println("Values:", values)}
Code explanation
Lines 5–15: The
extractKeysAndValuesfunction takes a map (inputMap) as an argument, iterates through its keys, and ...