Generic functions and maps

Report a typo

Anny wants to create a generic function keysToSlice. It should create and return a slice containing only the key values of a certain map.

Anny has already written a part of the code of the keysToSlice function. Your task is to help her write the additional code to finish the implementation of the keystoSlice generic function.

Sample Input 1:

Current Savings
1786.45 0.01

Sample Output 1:

[Current Savings]
Write a program in Go
package main

import (
"fmt"
"sort"
)

// Write the additional required code to finish the keysToSlice function.
func keysToSlice[K ?, V ?](in map[?]?) []? {
var mySlice []K

for key := range ? {
?
}
return mySlice
}

// DO NOT delete or modify the contents of the main function!
func main() {
var str1, str2 string
fmt.Scanln(&str1, &str2)

var num1, num2 float64
fmt.Scanln(&num1, &num2)

myMap := map[string]float64{str1: num1, str2: num2}
mySlice := keysToSlice(myMap)

sort.Slice(mySlice, func(i, j int) bool {
return mySlice[i] < mySlice[j]
})
fmt.Println(mySlice)
}
___

Create a free account to access the full topic