...

/

Solution 1: Composite Data Types

Solution 1: Composite Data Types

Let’s solve the challenges set in the previous lesson.

Problem 1: Solution

Here’s a sample Go program that converts a 2D array into a map:

Press + to interact
package main
import "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 convertToMap function iterates over each pair in the 2D array using a for loop, assigning the first element of the pair as the key and the second element as the value in the map m. Finally, it returns the resulting map.

  • Lines 13–17: The main function creates a 2D array of key-value pairs, arr, passes it to the convertToMap function to get a map of key-value pairs mp, and prints the resulting map to the console using the fmt.Println function.

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:

Press + to interact
package main
import "fmt"
func extractKeysAndValues(inputMap map[string]int) ([]string, []int) {
var keys []string
var values []int
for 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 extractKeysAndValues function takes a map (inputMap) as an argument, iterates through its keys, and ...