golang陣列分割

weixin_34419326發表於2018-05-23
package main

import (
    "util"
    "fmt"
    "time"
)

func main() {
    lista := []interface{}{}
    a := map[string]interface{}{}

    for num := 0; num < 30000; num++ {
        alphanumeric := util.RandomAlphanumeric(20)
        lista = append(lista, alphanumeric)
        a[util.RandomAlphanumeric(5)] = alphanumeric
        fmt.Println(alphanumeric)
    }
    segmens := splitArray(lista, 10)
    fmt.Println(len(segmens))

    for index,_ := range segmens{
        go func(a int) {
            fmt.Println(a, segmens[a])
        }(index)
    }
    time.Sleep(2000 * time.Millisecond)
}
//陣列平分
func splitArray(arr []interface{}, num int64) (segmens []interface{}) {
    max := int64(len(arr))
    if max < num {
        return arr
    }
    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
        segmens = append(segmens, arr[beg:end])
        fmt.Printf("beg:%v,end:%v\n", beg, end)
    }
    return
}

相關文章