Go - Maps

  • Declared: map[KeyType]ValueType
    • Ex. m := make(map[string]int)
      m["a"]=1
      m{"b"]=2
    • Ex. m := map[string]int {
         "a":1,
         "b":2, // Please notice every entry need to be end with comma
      }
  • Key type must be comparable using ==, array can be used as a key to declare a map, but slice is not acceptable.
    • Ex. array can be used as key
    • Ex. compile error when use slice as a key
  • Empty map, length of nil map is 0 as well, but you can't put entry to nil map
    • m := make(map[string]int)
      m := map[string]int{}
  • Ex. Delete entry
    m := map[string]int {
        "a":1,
        "b":2
    }
    delete(m, "a")
  • add 1 to key
  • add 1 to entry but key not exist, value will start from 0 because there is still an assignment
  • Can't get entry's address, because entry address may change after rehash.
    Will compile error when trying to get entry's address.
    Ex. keyP := &m["k"]
  • Iterate map by range, the order is random by design intent. To prevent client code depends on the implementation
  • If we want to follow order to iterate, need sort key and iterate key to get value
  • Zero value of map is nil
  • Store a value in map's zero value will panic!! Must allocate the map before using it
  • Get value from a nil map will get zero value of the type. 
  • Check key exist or not
  • m = make(map[string]map[string]int)



沒有留言:

張貼留言

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...