Tag Archives: Go map sorting

Quickly convert map to ordered array

    take out the key of map and put it into a slice s to sort and traverse, V: = range s, take the value: map [v] from the map and put it in the array in turn 0

    var err error
    msgs = make([]*configModel.SysMailMsg, len(cacheMap))
    keys := make([]int, len(cacheMap))
    
    i := 0
    for k, _ := range cacheMap {
       if keys[i], err = strconv.Atoi(k); err != nil {
          return nil, err
       }
       i++
    }
    sort.Ints(keys)
    mi := 0
    for _, v := range keys {
       var tmp configModel.SysMailMsg
       json.UnmarshalFromString(cacheMap[strconv.Itoa(v)], &tmp)
       msgs[mi] = &tmp
       mi++
    }