github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume1/section3/mapdemo/mapdemo.go (about)

     1  // An example of building a map having keys representing nations, and values representing
     2  // the respective nation's capital.
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  	"sort"
     8  )
     9  
    10  // An example of sorting the keys in a map alphabetically
    11  func printSortedNationCapitalsMap(capitalsMap map[string]string) {
    12  
    13  	keys := make([]string, len(capitalsMap))
    14  
    15  	for key, _ := range capitalsMap {
    16  		keys = append(keys, key)
    17  	}
    18  
    19  	sort.Strings(keys)
    20  
    21  	for _, v := range keys {
    22  		if v == "" {
    23  			continue
    24  		}
    25  		fmt.Println("The capital of", v, "is ", capitalsMap[v])
    26  	}
    27  
    28  }
    29  
    30  func printNationCapitalsMap(capitalsMap map[string]string) {
    31  
    32  	for key, value := range capitalsMap {
    33  		fmt.Println("The capital of", key, "is ", value)
    34  	}
    35  
    36  }
    37  
    38  func nationCapitalsExample() {
    39  
    40  	// Note: In Go, maps have no contract to maintain the order of the keys
    41  	var nationCapitals map[string]string = make(map[string]string)
    42  	nationCapitals["Afghanistan"] = "Kabul"
    43  	nationCapitals["Canada"] = "Ottawa"
    44  	nationCapitals["Japan"] = "Tokyo"
    45  	nationCapitals["Kenya"] = "Nairobi"
    46  	nationCapitals["India"] = "New Delhi"
    47  	nationCapitals["Mexico"] = "Mexico City"
    48  	nationCapitals["South Korea"] = "Seoul"
    49  	nationCapitals["United Kingdom"] = "London"
    50  	nationCapitals["USA"] = "Washington D.C."
    51  	nationCapitals["Taiwan"] = "Taipei"
    52  
    53  	fmt.Println("Print the map unsorted (random order): ")
    54  	printNationCapitalsMap(nationCapitals)
    55  	fmt.Println("\n")
    56  
    57  	fmt.Println("Print the map sorted by key (nation name):")
    58  	printSortedNationCapitalsMap(nationCapitals)
    59  	fmt.Println("\n")
    60  }
    61  
    62  func main() {
    63  
    64  	nationCapitalsExample()
    65  
    66  }