golang interface to []

case "bindList":
        type idsRequest struct {
            Ids []int
        }
        ids := new(idsRequest)
        cx.Fill(ids)
        hitStorehouses := make([]module.HitStorehouse, 0)
        goblet.DB.Where("status = ?",module.HitStorehouse_Status_Aliable).In("import_excel_id",ids.Ids).Find(&hitStorehouses)
        arrayInterface := splitArrayInterface(100, hitStorehouses)
        for index,_ := range arrayInterface {
            go func(i int) {
                for _, value := range arrayInterface[i] {
                    log.Println(value.(module.HitStorehouse).Id," ", value.(module.HitStorehouse).PhoneMd5," ", value.(module.HitStorehouse).PhoneHash," ", value.(module.HitStorehouse).ImportExcelId," ", value.(module.HitStorehouse).Status)

                }
            }(index)
        }





func splitArrayInterface( num int64,arr interface{}) (segmens [][]interface{}) {
    v := reflect.ValueOf(arr)
    max := int64(v.Len())
    fmt.Println("max:",max)
    ret := make([]interface{}, max)
    for i := 0; i < int(max); i++ {
        ret[i] = v.Index(i).Interface()
    }
    fmt.Println("ret:", len(ret))
    if max < num {
        segmens = append(segmens, ret)
        return
    }
    var step = max / num
    var beg int64
    var end int64

    for i := int64(0); i < num || end < max; i++ {
        beg = 0 + i*step
        end = beg + step
        if end > max {
            segmens = append(segmens, ret[beg:max])
        } else {
            segmens = append(segmens, ret[beg:end])
        }
        //fmt.Printf("beg:%v,end:%v\n", beg, end)
    }
    return
}
參考:https://segmentfault.com/q/1010000000198391
func ToSlice(arr interface{}) []interface{} {
    v := reflect.ValueOf(arr)
    if v.Kind() != reflect.Slice {
        panic("toslice arr not slice")
    }
      l := v.Len()
      ret := make([]interface{}, l)
    for i := 0; i < l; i++ {
        ret[i] = v.Index(i).Interface()
    }
    return ret
}
func ToStr(i interface{}) string {
  return fmt.Sprintf("%v", i)
}
ToStr(1)
ToStr(float64(1))
func Join(i []interface{}) string {
}
Join([]int{1,2})  // 報錯:類型不匹配
Join(ToSlice([]int{1,2}))
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容