doupa9062 2017-08-01 15:14
浏览 20
已采纳

使辅助函数通用

I created a small helper function to split a large array of items into smaller arrays with a maximum size of n.

func toPackages(e []int, n int) [][]int {
    var p [][]int
    packets := int(math.Ceil(float64(len(e)) / float64(n)))
    for i := 0; i < packets; i++ {
        start := i * n
        end := n * (i + 1)
        if len(e) < end {
            end = len(e)
        }
        p = append(p, e[start:end])
    }
    return p
}

Working example at Golang Playground.
In the program I have several different types of arrays I would like to split. I have tried converting it to using interfaces with interface{}.

  • 写回答

2条回答 默认 最新

  • douao2000 2017-08-01 15:23
    关注

    It is pretty hard to make a generic function to handle this well. You will often spend as much code converting []int to []interface{} and back, as it is to just copy the snippet. I do have a slightly nicer way to do it though:

    playground link

    func splitInts(src []int, n int) (p [][]int){
        for len(src) > n{
            p = append(p,src[:n])
            src = src[n:]
        }
        if(len(src) > 0){
            p = append(p,src)
        }
        return p
    }
    

    Nothing in the function changes because of types, it can easily be copied to:

    func splitStrings(src []string, n int) (p [][]string){
        for len(src) > n{
            p = append(p,src[:n])
            src = src[n:]
        }
        if(len(src) > 0){
            p = append(p,src)
        }
        return p
    }
    

    By only changing the first line.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?