Advertisement
cwchen

[Go] Memorizing the order of a map.

Sep 23rd, 2017
571
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.66 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func main() {
  6.     // Create an anomynous struct.
  7.     data := struct {
  8.         m     map[string]string
  9.         order []string
  10.     }{
  11.         m:     make(map[string]string),
  12.         order: []string{},
  13.     }
  14.  
  15.     // Insert several key/value pairs.
  16.     data.m["Go"] = "Beego"
  17.     data.order = append(data.order, "Go")
  18.  
  19.     data.m["Python"] = "Django"
  20.     data.order = append(data.order, "Python")
  21.  
  22.     data.m["Ruby"] = "Rails"
  23.     data.order = append(data.order, "Ruby")
  24.  
  25.     data.m["PHP"] = "Laravel"
  26.     data.order = append(data.order, "PHP")
  27.  
  28.     // Iterate these key/value pairs with order.
  29.     for _, e := range data.order {
  30.         fmt.Println(fmt.Sprintf("%s: %s", e, data.m[e]))
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement