split a map into two maps in go

To split a map into two maps, you need to iterate through the original map and add its key-value pairs to two separate maps based on a condition. Here's an example code snippet that splits a map into two maps based on a condition that checks if the key is even or odd:

main.go
func splitMapByKey(mapToSplit map[int]string) (map[int]string, map[int]string) {
    evenMap := make(map[int]string)
    oddMap := make(map[int]string)

    for key, value := range mapToSplit {
        if key%2 == 0 {
            evenMap[key] = value
        } else {
            oddMap[key] = value
        }
    }

    return evenMap, oddMap
}
346 chars
15 lines

Here, we declare two new maps evenMap and oddMap to store key-value pairs based on the condition. We then iterate through the original mapToSplit using range, and add each key-value pair to the appropriate map based on the condition key%2 == 0. Finally, the function returns the two split maps evenMap and oddMap.

gistlibby LogSnag